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

标签 python arrays numpy memory reshape

我想将 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/

相关文章:

php - 如何按条件过滤数组

python - 如何在 Python 中高效地生成 M 个随机二进制数组?

python - 导出Python脚本

python - 将数据从 Excel 导入到 Mysql Python

python - 编写一个程序,从大量(或少量)输入中提取K个最大值。

javascript - 如何在Javascript中将JSON字符串解析为数组

python - 在没有继承的情况下从另一个访问类属性?使用类数组作为输入

python - TypeError : int() argument must be a string or a number, 不是 'Model Instance'

python - 如何计算 Django 中的 Frechet 距离?

python - 使用数组作为多维数组的索引掩码