[英]How to stack uneven numpy arrays?
how can I stack the elements from the same respective index from each array in a list of arrays?如何在 arrays 列表中堆叠每个数组中相同索引的元素?
arrays = [np.array([1,2,3,4,5]),
np.array([6,7,8,9]),
np.array([11,22,33,44,55]),
np.array([2,4])]
output = [[1,6,11,2],
[2,7,22,4],
[3,8,33],
[4,9,44],
[5,55]]
arrays
is a list of arrays of uneven lengths. arrays
是长度不均匀的 arrays 的列表。 The output
has a first array (don't mind if it's a list too) that contains all possible index 0s from each array. output
有一个第一个数组(不介意它是否也是一个列表),其中包含每个数组中所有可能的索引 0。 The next array within output
contains all possible index 1s and so on... output
中的下一个数组包含所有可能的索引 1,依此类推...
Closest thing I can find (but requires same shape arrays) is:我能找到的最接近的东西(但需要相同的形状数组)是:
a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
np.stack((a, b), axis=-1)
# which gives
array([[1, 2],
[2, 3],
[3, 4]])
Thanks.谢谢。
You could just wrap it in a DataFrame first:您可以先将其包装在 DataFrame 中:
arr = pd.DataFrame(arrays).values.T
Output: Output:
array([[ 1., 6., 11., 2.],
[ 2., 7., 22., 4.],
[ 3., 8., 33., nan],
[ 4., 9., 44., nan],
[ 5., nan, 55., nan]])
Though if you really want it with different sizes, go with:虽然如果您真的想要不同尺寸的 go 与:
arr = [x.dropna().values for _, x in pd.DataFrame(arrays).iteritems()]
Output: Output:
[array([ 1, 6, 11, 2]),
array([ 2, 7, 22, 4]),
array([ 3., 8., 33.]),
array([ 4., 9., 44.]),
array([ 5., 55.])]
This gets you close.这让你接近。 You can't really have a 2D sparse array as shown in your example output.
您不能真正拥有如示例 output 中所示的二维稀疏数组。
import numpy as np
arrays = [np.array([1,2,3,4,5]),
np.array([6,7,8,9]),
np.array([11,22,33,44,55]),
np.array([2,4])]
maxx = max(x.shape[0] for x in arrays)
for x in arrays:
x.resize(maxx,refcheck=False)
output = np.stack(arrays, axis=1)
print(output)
C:\tmp>python x.py
[[ 1 6 11 2]
[ 2 7 22 4]
[ 3 8 33 0]
[ 4 9 44 0]
[ 5 0 55 0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.