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

标签 python arrays numpy memory

我有一个 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 列表,在将其复制到新分配的数组后会被丢弃。多一份副本(数组到连续数组)可能没什么大不了的......

关于python - 无需重新排列内存的 3×n 数组的紧凑规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46686129/

相关文章:

python - 如何将 .csv 文件转换为不同类型的 numpy 数组

python - 如何运行创建一个discord.py机器人命令,该命令将使用不同的参数多次运行另一个机器人命令?

python - 在 Pandas 时间序列数据框中删除重复项

javascript - 使用 .map() 和 .get() 命名数组键

c++ - 为什么在动态分配的数组上调用 delete 会导致一个崩溃而不是另一个?

python - 将一维点列表转换为二维 np 数组

python - 如何规范化 4D numpy 数组?

python - 使用 numpy 数组时,struct.pack 在 python 2.6 中要慢得多

python - sympy.plotting.plot 奇怪的 xlabel 位置

C++搜索数组中的最大数字