python - View 不适用于转置数组

标签 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)],
   [(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
array([[10, 20],
   [11, 21],
   [11, 21],
   [12, 22],
   [13, 23]])
>>>  f.view([('',f.dtype)]*f.shape[1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: new type not compatible with array.

最佳答案

默认情况下,您的 numpy 数组存储在内存中 row major order 中的单个连续 block 中。定义结构化数组时,所有字段在内存中也必须是连续的。在您的情况下,您要求将每一行存储在内存中的连续位置。当您转置数组时,不会打乱数据,只会更改步幅,这意味着现在列存储在内存中的连续位置。

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

>>> 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')])

关于python - View 不适用于转置数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17409122/

相关文章:

python - Django-inspectdb- "models.FileField"显示为 "models.CharField"

html - 切换到以前的 IFRAME Selenium Python

python - 如何修复 Python 中的双重编码和损坏的字符串?

python-2.7 - 使用 Pandas 对二维数据框进行排序

python - Python中前一个和后一个元素相乘

python 3.4 py2exe image.open 找不到图像

python - 忽略指定值的 numpy 数组的平均值

python - 如何移除移动物体以仅获取背景?

python - 与python匹配的scipy方法

python - 导入错误 : DLL load failed: The specified module could not be found (sklearn)