【问题标题】:How to loop through a nested numpy array to obtain column-wise values如何遍历嵌套的 numpy 数组以获取按列的值
【发布时间】:2020-03-21 20:15:18
【问题描述】:

我有一个输入numpy数组如下:

import numpy as np

my_array = [
        np.array([[[1,  10]],
                 [[2,  11]]], dtype=np.int32),
        np.array([[[3, 12]],
                  [[4, 13]],
                  [[5, 14]]], dtype=np.int32),
        np.array([[[6,  15]],
                  [[7,  16]],
                  [[8,  17]]], dtype=np.int32)
]

我想得到两个数组(每列 1 个),这样:

array1 = [1, 2, 3, 4, 5, 6, 7 ,8]
array2 = [10, 11, 12, 13, 14, 15, 16, 17]

我尝试了列表理解,但没有成功:

[col[:] for col in my_array]

【问题讨论】:

    标签: python numpy numpy-ndarray


    【解决方案1】:

    您可以遍历数组并附加到新数组:

    array1 = []
    array2 = []
    
    for array in my_array:
      for nested_array in array:
        # nested_array is of form [[ 1 10]] here, you need to index it
        # first with [0] then with the element you want to access [0] or [1]
        array1.append(nested_array[0][0])
        array2.append(nested_array[0][1])
    

    您只需要考虑输入数据的结构以及如何按照您需要的顺序获取所需的值。

    输出:

    >>> array1
    [1, 2, 3, 4, 5, 6, 7, 8]
    >>> array2
    [10, 11, 12, 13, 14, 15, 16, 17]
    

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      >>> from numpy import array
      >>> import numpy as np
      >>> my_array = [array([[[1,  10]],
              [[2,  11]]], dtype='int32'), array([[[3, 12]],
      
              [[4, 13]],
              [[5, 14]]], dtype='int32'), array([[[6,  15]],
      
              [[7,  16]],
              [[8,  17]]], dtype='int32')]
      # One way
      >>> np.concatenate(my_array,axis=0)[...,0]    # [...,1] would give the other one
      array([[1],
             [2],
             [3],
             [4],
             [5],
             [6],
             [7],
             [8]], dtype=int32)
      # Other way:
      >>> np.concatenate(my_array,axis=0)[...,0].reshape(-1,) # [...,1].reshape(-1,0) would be the other one
      array([1, 2, 3, 4, 5, 6, 7, 8], dtype=int32)
      

      【讨论】:

        猜你喜欢
        • 2012-04-26
        • 2021-08-18
        • 2010-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多