他们是否可以使用第1列作为索引将单个2d数组拆分为多个不同形状的1d数组?

问题描述 投票:0回答:2

我正在尝试使用第一列作为索引将2d numpy数组拆分为第2列的多个1d数组。 2d阵列非常大(2,100000)

基本上我有一个看起来像这样的数组(只是更大):

[[1,a]
 [1,a2]
 [1,a3]
  ....
 [100,b]
 [100,b2]]

我想把它分成两个看起来像的数组

[a,a2,a3]

[b,b2]

我甚至不确定从哪里开始或搜索,并非常感谢任何帮助

python arrays numpy sorting
2个回答
0
投票

你在找itertools.groupby。您需要指定一个key函数,该函数指定如何对嵌套list中的元素进行分组(在本例中为第一个元素)。在这种情况下,我们可以使用itemgetter

根据您的要求,您只希望每个组都包含原始数据的第二个元素,因此itemgetter也可以提供帮助。

from itertools import groupby
from operator import itemgetter

data = [[1, 'a'],
        [1, 'b'],
        [1, 'c'],
        [2, 'a'],
        [2, 'b'],
        [3, 'c']]

result = {key: list(map(itemgetter(1), group)) for key, group in groupby(data, key=itemgetter(0))}

print(result)

输出:

{1: ['a', 'b', 'c'], 2: ['a', 'b'], 3: ['c']}

请注意,如果键尚未按顺序排列,则应首先对输入嵌套的list进行排序,否则它们将被拆分为具有相同键的多个组。


0
投票

您可以使用np.flatnonzero(或np.nonzeronp.where)和np.diff查找块边界,然后使用np.split进行拆分:

# create example
x = np.c_[np.repeat(*sum(np.ogrid[:2, 1:4])), 1:10]
x
# array([[1, 1],
#        [1, 2],
#        [2, 3],
#        [2, 4],
#        [2, 5],
#        [3, 6],
#        [3, 7],
#        [3, 8],
#        [3, 9]])
np.split(x[:, 1], np.flatnonzero(np.diff(x[:, 0])) + 1)
# [array([1, 2]), array([3, 4, 5]), array([6, 7, 8, 9])]
© www.soinside.com 2019 - 2024. All rights reserved.