无法构造numpy的阵列

问题描述:

虽然试图结构numpy的阵列内减去在字段内进行减去的特定字段,则出现下列错误:无法构造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')]) 

鉴于标准浮法D型,为什么将无法执行此减法?

要重现这些条件下,以下示例代码提供了:

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 

任何建议,将不胜感激!

dtypeserPos['pos']是化合物

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

减法(以及类似的操作),用于D类化合物还没有被定义。它不适用于raw dtype。

你可以减去各个领域

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

我认为,我们还viewserPos['pos']为2D阵列(3列),可以和减去形式。但我需要测试语法。

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

应产生一个(N,3)二维阵列。

+0

谢谢hpaulj澄清这一点。 我也可以通过将'np.dtype'改为 'raw = np.dtype([('residue',int),('pos','(1,3)f8')来解决这个问题。 )])' 现在'serPos ['pos'] - hisPos ['pos']'完美地工作。 干杯! –

+0

我会用''(3,)f8''所以'serPos ['pos']'是'(N,3)',而不是'(N,1,3)'。 – hpaulj