【问题标题】:Is their a way to split a single 2d array into multiple 1d arrays of various shapes using the 1st column as an index?他们是使用第一列作为索引将单个二维数组拆分为多个不同形状的一维数组的方法吗?
【发布时间】:2019-04-14 04:21:26
【问题描述】:

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

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

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

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

[a,a2,a3]

[b,b2]

我什至不确定从哪里开始或搜索,如果有任何帮助,我将不胜感激

【问题讨论】:

    标签: python arrays numpy sorting


    【解决方案1】:

    您正在寻找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 的输入进行排序,否则将使用相同的键将它们分成多个组。

    【讨论】:

      【解决方案2】:

      您可以使用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])]
      

      【讨论】:

        猜你喜欢
        • 2019-05-22
        • 2014-08-28
        • 2020-11-18
        • 2021-06-04
        • 1970-01-01
        • 2021-08-14
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        相关资源
        最近更新 更多