我有一个输入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]
答案 0 :(得分:1)
您可以尝试以下方法:
>>> 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)
答案 1 :(得分: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]