Python 视图不适用于转置数组

Python 视图不适用于转置数组,python,python-2.7,numpy,Python,Python 2.7,Numpy,为什么这样做有效: >>> f = np.array(([[10,20],[11,21],[11,21],[12,22],[13,23]])) >>> f array([[10, 20], [11, 21], [11, 21], [12, 22], [13, 23]]) >>> f.view([('',f.dtype)]*f.shape[1]) array([[(10, 20)], [(11, 21)],

为什么这样做有效:

>>> f = np.array(([[10,20],[11,21],[11,21],[12,22],[13,23]]))
>>> f
array([[10, 20],
   [11, 21],
   [11, 21],
   [12, 22],
   [13, 23]])
>>> f.view([('',f.dtype)]*f.shape[1])
array([[(10, 20)],
   [(11, 21)],
   [(11, 21)],
   [(12, 22)],
   [(13, 23)]], 
  dtype=[('f0', '<i8'), ('f1', '<i8')])
>>f=np.array([10,20]、[11,21]、[11,21]、[12,22]、[13,23]]))
>>>f
数组([[10,20],
[11, 21],
[11, 21],
[12, 22],
[13, 23]])
>>>视图([('',f.dtype)]*f.shape[1])
数组([(10,20)],
[(11, 21)],
[(11, 21)],
[(12, 22)],
[(13, 23)]], 

dtype=[('f0','这是内存布局问题:

>>> f = np.array(([[10,20],[11,21],[11,21],[12,22],[13,23]]))
>>> f.flags.c_contiguous
True
>>> f = np.array(([10,11,11,12,13],[20,21,21,22,23])).T
>>> f.flags.c_contiguous
False
>>> f.view([('',f.dtype)]*f.shape[0])
array([[(10, 11, 11, 12, 13), (20, 21, 21, 22, 23)]], 
      dtype=[('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<i8'), ('f4', '<i8')])
>>f=np.array([10,20]、[11,21]、[11,21]、[12,22]、[13,23]]))
>>>f.flags.c_
真的
>>>f=np.数组([10,11,11,12,13],[20,21,21,22,23]).T
>>>f.flags.c_
假的
>>>f.视图([('',f.dtype)]*f.形状[0])
数组([(10,11,11,12,13),(20,21,21,22,23)],

数据类型=[('f0','默认情况下,您的numpy数组存储在内存中的单个连续块中。定义结构化数组时,所有字段在内存中也必须连续。在您的情况下,您需要将每一行存储在内存中的连续位置。当您转置数组时,而不是将数据四处乱洗,只有跨步是连续的anged,这意味着现在是存储在内存中连续位置的列

虽然可能需要复制数据,但速度很慢,安全的方法是在执行结构数组魔术之前调用
np.ascontiguousarray

>>> f = np.array([[10,11,11,12,13],[20,21,21,22,23]]).T
>>> f = np.ascontiguousarray(f)
>>> f.view([('',f.dtype)]*f.shape[1])
array([[(10, 20)],
       [(11, 21)],
       [(11, 21)],
       [(12, 22)],
       [(13, 23)]], 
      dtype=[('f0', '<i4'), ('f1', '<i4')])
>>f=np.array([[10,11,11,12,13],[20,21,21,22,23]]).T
>>>f=np.ASCONTIGOUUSARRAY(f)
>>>视图([('',f.dtype)]*f.shape[1])
数组([(10,20)],
[(11, 21)],
[(11, 21)],
[(12, 22)],
[(13, 23)]], 
dtype=[('f0','+1)以获得清晰的解释(而我的答案是含糊不清的!),尽管我仍然认为,如果可能,应该通过构造具有正确内存布局的数组来避免
np.ascontiguousarray
>>> f = np.array(([10,11,11,12,13],[20,21,21,22,23]), order='F').T
>>> f.flags.c_contiguous
True
>>> f.view([('',f.dtype)]*f.shape[1])
array([[(10, 20)],
       [(11, 21)],
       [(11, 21)],
       [(12, 22)],
       [(13, 23)]], 
      dtype=[('f0', '<i8'), ('f1', '<i8')])
>>> f = np.array([[10,11,11,12,13],[20,21,21,22,23]]).T
>>> f = np.ascontiguousarray(f)
>>> f.view([('',f.dtype)]*f.shape[1])
array([[(10, 20)],
       [(11, 21)],
       [(11, 21)],
       [(12, 22)],
       [(13, 23)]], 
      dtype=[('f0', '<i4'), ('f1', '<i4')])