以Fortran连续顺序重塑numpy.array

以Fortran连续顺序重塑numpy.array

问题描述:

我有一个如下数组,

from numpy import *
a=array([1,2,3,4,5,6,7,8,9])

我想得到如下结果

[[1,4,7],[2,5,8],[3,6,9]]

因为我有很多东西.所以我需要一种有效的方法来做到这一点. 最好是就地重塑它.

Because I have a big array. So i need a efficient way to do it . And it's better to reshape it in-place.

您可以使用reshape传递order='F'.只要有可能,返回的数组将只是原始视图的一个视图,而不会复制数据,例如:

You can use reshape passing order='F'. Whenever possible, the returned array will be only a view of the original one, without data being copied, for example:

a = np.arange(1, 10)
# array([1, 2, 3, 4, 5, 6, 7, 8, 9])
b = a.reshape(3, 3)
c = a.reshape(3, 3, order='F')

a[0] = 11

print(b)
#array([[ 11,  4,  7],
#       [ 2,  5,  8],
#       [ 3,  6,  9]])

print(c)
#array([[ 11,  4,  7],
#       [ 2,  5,  8],
#       [ 3,  6,  9]])

flags属性可用于检查数组的内存顺序和数据所有权:

The flags property can be used to check the memory order and data ownership of an array:

print(a.flags)
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

print(b.flags)
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

print(c.flags)
  C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False