我正在用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="->")
)效果很好。但是,如果我在同一位置上有元素,它将在彼此上叠加多个箭头,也就是说,如果我有positions = [1,1,4,4]和forces = [4,5,8,9],它将在位置1处形成两个箭头,在位置4上形成两个箭头,在彼此之上。相反,我想把力相加,只在位置1处用力4+5=9创建一个箭头,在位置4处用力8+9=17创建一个箭头。
我如何用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发布于 2015-05-06 18:02:23
我不确定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, ufhttps://stackoverflow.com/questions/30083605
复制相似问题