如何在嵌套的numpy数组中循环以获得按列的值

2024-04-20 05:50:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个输入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]

Tags: inimportnumpy列表formyasnp
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)

您可以在数组中循环并附加到新数组:

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]

相关问题 更多 >