【问题标题】:Unable to subtract specific fields within structured numpy arrays无法减去结构化 numpy 数组中的特定字段
【发布时间】:2016-12-07 22:40:18
【问题描述】:

在尝试减去结构化 numpy 数组中的字段时,出现以下错误:

In [8]: print serPos['pos'] - hisPos['pos']
--------------------------------------------------------------------------- 
TypeError                                 
Traceback (most recent call last) <ipython-input-8-8a22559cfb2d> in <module>()
----> 1 print serPos['pos'] - hisPos['pos']

TypeError: ufunc 'subtract' did not contain a loop with signature matching types 
dtype([('x', '<f8'), ('y', '<f8'), ('z', '<f8')]) 
dtype([('x', '<f8'), ('y', '<f8'), ('z', '<f8')]) 
dtype([('x', '<f8'), ('y', '<f8'), ('z', '<f8')])

鉴于标准 float dtype,为什么我无法执行此减法?

为了重现这些情况,提供了以下示例代码:

import numpy as np

raw = np.dtype([('residue', int),
    ('pos', [('x', float),
    ('y', float),
    ('z', float)])])

serPos = np.empty([0,2],dtype=raw)
hisPos = np.empty([0,2],dtype=raw)

serPos = np.append(serPos, np.array([(1,(1,2,3))], dtype=raw))
hisPos = np.append(hisPos, np.array([(1,(1,2,3))], dtype=raw))

print serPos['pos'], hisPos['pos']  # prints fine
print serPos['pos'] - hisPos['pos'] # errors with ufunc error

任何建议将不胜感激!

【问题讨论】:

    标签: python arrays python-2.7 numpy


    【解决方案1】:

    serPos['pos']dtype 是复合词

    dtype([('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
    

    减法(和其他此类操作)尚未为复合 dtype 定义。它也不适用于 raw dtype。

    您可以减去单个字段

    serPos['pos']['x']-hisPos['pos']['x']
    

    我认为我们也可以将 view serPos['pos'] 作为二维数组(3 列)并减去该形式。但我需要测试语法。

    serPos['pos'].view((float,(3,)))
    

    应该产生一个(N,3) 2d 数组。

    【讨论】:

    • 感谢 hpaulj 澄清这一点。我还可以通过将np.dtype 更改为raw = np.dtype([('residue', int),('pos','(1,3)f8')]) 来解决这个问题,现在serPos['pos'] - hisPos['pos'] 可以完美运行。干杯!
    • 我会使用'(3,)f8' 所以serPos['pos'](N,3) 而不是(N,1,3)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多