gpt4 book ai didi

python - 我可以在不复制数据的情况下组合 NumPy 数组中的非相邻维度吗?

转载 作者:行者123 更新时间:2023-11-30 21:53:17 26 4
gpt4 key购买 nike

我想将 3-D NumPy 数组的第一个和最后一个维度合并为一个维度,而不复制数据:

import numpy as np

data = np.empty((3, 4, 5))
data = data.transpose([0, 2, 1])

try:
# this fails, indicating that it is not possible:
# AttributeError: incompatible shape for a non-contiguous array
data.shape = (-1, 4)
except AttributeError:
# this creates a copy of the data:
data = data.reshape((-1, 4))

这可能吗?

最佳答案

In [55]: arr = np.arange(24).reshape(2,3,4)                                                               
In [56]: arr1 = arr.transpose(2,1,0)
In [57]: arr
Out[57]:
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]]])
In [58]: arr1
Out[58]:
array([[[ 0, 12],
[ 4, 16],
[ 8, 20]],

[[ 1, 13],
[ 5, 17],
[ 9, 21]],

[[ 2, 14],
[ 6, 18],
[10, 22]],

[[ 3, 15],
[ 7, 19],
[11, 23]]])

看看这些值是如何在一维数据缓冲区中布局的:

In [59]: arr.ravel()                                                                                      
Out[59]:
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])

比较转置后的顺序:

In [60]: arr1.ravel()                                                                                     
Out[60]:
array([ 0, 12, 4, 16, 8, 20, 1, 13, 5, 17, 9, 21, 2, 14, 6, 18, 10,
22, 3, 15, 7, 19, 11, 23])

如果解析的值没有相同的顺序,则无法避免复制。

reshape 有以下注释:

You can think of reshaping as first raveling the array (using the given index order), then inserting the elements from the raveled array into the new array using the same kind of index ordering as was used for the raveling.

In [63]: arr1.reshape(-1,2)                                                                               
Out[63]:
array([[ 0, 12],
[ 4, 16],
[ 8, 20],
[ 1, 13],
[ 5, 17],
[ 9, 21],
[ 2, 14],
[ 6, 18],
[10, 22],
[ 3, 15],
[ 7, 19],
[11, 23]])

关于python - 我可以在不复制数据的情况下组合 NumPy 数组中的非相邻维度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59720590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com