所以说我有一个任意维度的数组(目前,我们将给它三个维度)。
a=array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]],
[[16, 17, 18, 19],
[20, 21, 22, 23]]])
将数组拆分为所有不同轴上的二维数组(在此例中为n-1,但为2)的最简单方法是什么。
new_array1=[[0, 1, 2, 3,], [4, 5, 6, 7]...[20, 21, 22, 23]]
new_array2=[[0, 4], [1, 5]...[19, 23]]
new_array3=[[0, 8, 16], [1, 9, 17]...[7, 15, 23]]
有没有简单的方法可以对任意维数的数组执行此操作?
答案 0 :(得分:0)
尝试一下:
b = []
for i in a:
b.append([item for sublist in i for item in sublist])
输出:
[[0, 1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 13, 14, 15],
[16, 17, 18, 19, 20, 21, 22, 23]]
答案 1 :(得分:0)
您可以将numpy的swapaxes()
与reshape()
结合使用来制作任意形状。
例如:
axis = 1
a.swapaxes(axis,2).reshape(-1,a.shape[axis])
> array([[ 0, 4],
[ 1, 5],
[ 2, 6],
[ 3, 7],
[ 8, 12],
[ 9, 13],
[10, 14],
[11, 15],
[16, 20],
[17, 21],
[18, 22],
[19, 23]])
和
axis = 0
a.swapaxes(axis,2).reshape(-1, a.shape[axis])
>array([[ 0, 8, 16],
[ 4, 12, 20],
[ 1, 9, 17],
[ 5, 13, 21],
[ 2, 10, 18],
[ 6, 14, 22],
[ 3, 11, 19],
[ 7, 15, 23]])
第一个示例可以通过重塑来完成,因为它具有相同的轴:
a.reshape(-1,4)
> array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]])
答案 2 :(得分:0)
您可以使用moveaxis和整形:
>>> from pprint import pprint
>>> import numpy as np
>>>
>>> a = sum(np.ogrid[:2, :30:10, :400:100])
>>> a
array([[[ 0, 100, 200, 300],
[ 10, 110, 210, 310],
[ 20, 120, 220, 320]],
[[ 1, 101, 201, 301],
[ 11, 111, 211, 311],
[ 21, 121, 221, 321]]])
>>>
>>> pprint([np.moveaxis(a, j, -1).reshape(-1, d) for j, d in enumerate(a.shape)])
[array([[ 0, 1],
[100, 101],
[200, 201],
[300, 301],
[ 10, 11],
[110, 111],
[210, 211],
[310, 311],
[ 20, 21],
[120, 121],
[220, 221],
[320, 321]]),
array([[ 0, 10, 20],
[100, 110, 120],
[200, 210, 220],
[300, 310, 320],
[ 1, 11, 21],
[101, 111, 121],
[201, 211, 221],
[301, 311, 321]]),
array([[ 0, 100, 200, 300],
[ 10, 110, 210, 310],
[ 20, 120, 220, 320],
[ 1, 101, 201, 301],
[ 11, 111, 211, 311],
[ 21, 121, 221, 321]])]
moveaxis和swapaxes的区别在于,moveaxis保留了其余尺寸的顺序。
答案 3 :(得分:0)
尝试一下:
b = list(map(lambda x:x.tolist(),np.split(a.flatten(),3)))
或者:
b = [i.tolist() for i in np.split(a.flatten(),3)]
或者:
b = list(map(lambda x:np.concatenate(x).tolist(),a))
或者:
b = [np.concatenate(i).tolist() for i in a]
所有情况:
print(b)
输出:
[[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23]]
答案 4 :(得分:0)
第一个:
a1 = [j for i in range(3) for j in a[i]]
第二个:
a2 = [list(zip(i[0], i[1])) for i in a]
第三个:
a3 = [list(zip(a[0][j], a[1][j], a[2][j])) for j in range(2)]