因此,假设我有一个任意维数的数组(现在,我们将其设为三维)。
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]]])将这个数组分成跨所有不同轴的2维数组(本例中是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]]对于任意维数的数组,有没有简单的方法可以做到这一点?
发布于 2018-10-22 13:14:02
试试这个:
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]]发布于 2018-10-22 13:24:50
您可以在reshape()中使用numpy的swapaxes()来制作这些形状。
例如:
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]])发布于 2018-10-22 13:44:16
您可以使用moveaxis和reshape:
>>> 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保留了其余维度的顺序。
https://stackoverflow.com/questions/52922690
复制相似问题