使用NumPy对数组中的元素求和

时间:2021-12-14 01:42:47

I am annotating a plot with matplotlib with this code

我用这段代码用matplotlib注释了一个情节

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="->")
    )

It works fine. But if I have elements at the same position, it will stack multiple arrows on each other, i.e. if I have positions = [1,1,4,4] and forces = [4,5,8,9], it will make two arrow at position 1 and two arrows at position 4, on top of each other. Instead, I want to sum the forces and only create one arrow at position 1 with force 4+5=9 and one arrow at position 4 with force 8+9=17.

它工作正常。但是如果我在同一个位置有元素,它会相互堆叠多个箭头,即如果我有位置= [1,1,4,4]和力= [4,5,8,9],它会使位置1处的两个箭头和位置4处的两个箭头位于彼此的顶部。相反,我想要对力进行求和,并且仅在力4 + 5 = 9时在位置1处创建一个箭头,在力4 + 9 = 17时在位置4处创建一个箭头。

How can I do this with Python and NumPy?

我怎么能用Python和NumPy做到这一点?

Edit

I guess it could be something like

我猜它可能是这样的

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

1 个解决方案

#1


I'm not sure numpy offers help. Here's a Python solution:

我不确定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

Edit: I'm not sure what "I have to do it with numpy" means, but

编辑:我不确定“我必须用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

#1


I'm not sure numpy offers help. Here's a Python solution:

我不确定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

Edit: I'm not sure what "I have to do it with numpy" means, but

编辑:我不确定“我必须用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