2016-08-02 44 views
2

雖然試圖結構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 

任何建議,將不勝感激!

回答

1

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