2015-05-06 23 views
0

我註釋與matplotlib陰謀與此代碼和元素與NumPy的

for position, force in np.nditer([positions, forces]): 
    plt.annotate(
     "%.3g N" % force, 
     xy=(position, 3), 
     xycoords='data', 
     xytext=(position, 2.5), 
     textcoords='data', 
     horizontalalignment='center', 
     arrowprops=dict(arrowstyle="->") 
    ) 

它工作正常。但是,如果我的元素位於相同的位置,它將堆疊多個箭頭,即如果我有positions = [1,1,4,4]forces = [4,5,8,9],它將在位置1處形成兩個箭頭,並在位置4處形成兩個箭頭,在彼此的頂部。相反,我想對力量進行求和,只在力位4 + 5 = 9時在位置1創建一個箭頭,在力位8 + 9 = 17時在位置4創建一個箭頭。

我該怎麼用Python和NumPy來做到這一點?

編輯

我想這可能是這樣的

import numpy as np 

positions = np.array([1,1,4,4]) 
forces = np.array([4,5,8,9]) 

new_positions = np.unique(positions) 
new_forces = np.zeros(new_positions.shape) 

for position, force in np.nditer([positions, forces]): 
    pass 
+2

我不知道是否有一個更好的標題這個題。對我來說,「數組中的元素和」只是意味着'np.sum(array)',但這顯然不是這樣的。 – Iguananaut

回答

3

我不知道numpy提供幫助。下面是一個Python的解決方案:

from collections import defaultdict 
result = defaultdict(int) 
for p,f in zip(positions,forces): 
    result[p] += f 

positions, forces = zip(*result.items()) 
print positions, forces 

編輯: 我不知道什麼是「我與numpy的去做」的意思,但

import numpy as np 
positions = np.array([1,1,4,4]) 
forces = np.array([4,5,8,9]) 
up = np.unique(positions) 
uf = np.fromiter((forces[positions == val].sum() for val in up), dtype=int) 

print up, uf 
+0

這是一個很好的解決方案,但我必須用numpy來做。你認爲你的代碼可以用numpy編寫嗎?我試圖在我的編輯 – Jamgreen

+0

完成一些代碼!謝謝:-D – Jamgreen