【问题标题】:Sum elements in array with NumPy使用 NumPy 对数组中的元素求和
【发布时间】:2015-05-06 17:25:04
【问题描述】:

我正在用 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

【问题讨论】:

  • 我想知道这个问题是否有更好的标题。对我来说,“对数组中的元素求和”只是意味着np.sum(array),但这显然不是这个意思。

标签: python arrays numpy matplotlib


【解决方案1】:

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

【讨论】:

  • 这是一个很好的解决方案,但我必须使用 numpy.你认为你的代码可以用 numpy 编写吗?我试图在我的编辑中制作一些代码
  • 完美!谢谢:-D
猜你喜欢
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多