Skip to main content
 首页 » 编程设计

python之无需重新排列内存的 3×n 数组的紧凑规范

2025年01月19日13mayingbao

我有一个 3 x n numpy 数组,其中包含显式指定的大 n,例如,

import numpy 
 
a = numpy.array([ 
  [ 
      +0.000867019185663, 
      +0.011660052716448, 
      +0.022876936356421, 
      +0.030448982673938, 
      # [...] 
  ], [ 
      0.500950464352200, 
      0.488212957934729, 
      0.455136681950283, 
      0.455136681950283, 
      # [...] 
  ], [ 
      0.600950464352200, 
      0.188212957934729, 
      0.155136681950283, 
      0.188212957934729, 
      # [...] 
  ]]) 

为了使代码更紧凑,我通常将a指定为转置

a = numpy.array([ 
  [+0.000867019185663, 0.500950464352200, 0.600950464352200], 
  [+0.011660052716448, 0.488212957934729, 0.188212957934729], 
  [+0.022876936356421, 0.455136681950283, 0.155136681950283], 
  [+0.030448982673938, 0.401996259318289, 0.101996259318289], 
  # [...] 
  ]).T 

但是,这给了我一个不连续的数组。我当然可以通过 numpy.ascontiguousarray(或 transpose() 而不是 T)使其连续,但我想避免重新排列内存。

有没有办法以紧凑的形式指定a,同时仍然得到形状为(3, n)的连续数组?

请您参考如下方法:

如果您以 Fortran 顺序(主要列)指定数组,则在转置后它将是 C 连续的。

例子:

x = np.array([[1, 2, 3], [4, 5, 6]], order='F').T 
 
# verification 
y = np.ascontiguousarray(x)  # should not make a copy if x is contiguous 
y[1] = 42  # modify y 
print(x)  # x has changed (no copy was made) 

反例:

x = np.array([[1, 2, 3], [4, 5, 6]], order='C').T 
 
# verification 
y = np.ascontiguousarray(x)  # should make a copy if x is not contiguous 
y[1] = 42  # modify y 
print(x)  # x has *not* changed (it was copied into y) 

备注:

我认为在这个阶段避免内存重排没有太大的实用值(value)。像这样初始化数组首先会创建一个 Python 列表,在将其复制到新分配的数组后会被丢弃。多一份副本(数组到连续数组)可能没什么大不了的......