numpy 数组行专业和列专业 [英] numpy array row major and column major
问题描述
我无法理解 numpy
如何存储其数据.考虑以下几点:
这表示 a
是列主要 (F_CONTIGUOUS
) 因此,在内部,a
应该如下所示:
[1, 4, 2, 5, 3, 6]
这正是本词汇表中所述的内容.令我困惑的是,如果我尝试以线性方式访问 a
的数据,我会得到:
此时我不确定 F_CONTIGUOUS
标志告诉我们什么,因为它不遵守顺序.显然,python 中的所有内容都是行主要的,当我们想以线性方式迭代时,我们可以使用迭代器 flat
.
问题如下:假设我们有一个数字列表,比如说:1, 2, 3, 4, 5, 6
,我们如何创建一个 numpy
形状的数组 (2, 3)
按列主要顺序排列?那就是我怎样才能得到一个看起来像这样的矩阵
array([[ 1., 3., 5.],[ 2., 4., 6.]])
我真的很希望能够对列表进行线性迭代并将它们放入新创建的 ndarray
.这样做的原因是因为我将读取按列主要顺序设置的多维数组文件.
numpy 按行主序存储数据.
<预><代码>>>>a = np.array([[1,2,3,4], [5,6,7,8]])>>>一个形状(2, 4)>>>a.shape = 4,2>>>一种数组([[1, 2],[3, 4],[5, 6],[7, 8]])如果改变形状,数据的顺序不会改变.
如果你加一个'F',你就可以得到你想要的.
<预><代码>>>>乙数组([1, 2, 3, 4, 5, 6])>>>c = b.reshape(2,3,order='F')>>>C数组([[1, 3, 5],[2, 4, 6]])I'm having trouble understanding how numpy
stores its data. Consider the following:
>>> import numpy as np
>>> a = np.ndarray(shape=(2,3), order='F')
>>> for i in xrange(6): a.itemset(i, i+1)
...
>>> a
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
>>> a.flags
C_CONTIGUOUS : False
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
This says that a
is column major (F_CONTIGUOUS
) thus, internally, a
should look like the following:
[1, 4, 2, 5, 3, 6]
This is just what it is stated in in this glossary. What is confusing me is that if I try to to access the data of a
in a linear fashion instead I get:
>>> for i in xrange(6): print a.item(i)
...
1.0
2.0
3.0
4.0
5.0
6.0
At this point I'm not sure what the F_CONTIGUOUS
flag tells us since it does not honor the ordering. Apparently everything in python is row major and when we want to iterate in a linear fashion we can use the iterator flat
.
The question is the following: given that we have a list of numbers, say: 1, 2, 3, 4, 5, 6
, how can we create a numpy
array of shape (2, 3)
in column major order? That is how can I get a matrix that looks like this
array([[ 1., 3., 5.],
[ 2., 4., 6.]])
I would really like to be able to iterate linearly over the list and place them into the newly created ndarray
. The reason for this is because I will be reading files of multidimensional arrays set in column major order.
The numpy stores data in row major order.
>>> a = np.array([[1,2,3,4], [5,6,7,8]])
>>> a.shape
(2, 4)
>>> a.shape = 4,2
>>> a
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
If you change the shape, the order of data do not change.
If you add a 'F', you can get what you want.
>>> b
array([1, 2, 3, 4, 5, 6])
>>> c = b.reshape(2,3,order='F')
>>> c
array([[1, 3, 5],
[2, 4, 6]])
这篇关于numpy 数组行专业和列专业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!