Python numpy数组对某些索引求和 [英] Python numpy array sum over certain indices

查看:199
本文介绍了Python numpy数组对某些索引求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅对 numpy 数组上的索引列表执行求和,例如,如果我有一个数组 a = [1,2,3,4] 和要求和的索引列表, indices = [0, 2] 我想要一个快速的操作来给我答案 4 因为在 中索引 0 和索引 2 处的值求和的值a4

How to perform a sum just for a list of indices over numpy array, e.g., if I have an array a = [1,2,3,4] and a list of indices to sum, indices = [0, 2] and I want a fast operation to give me the answer 4 because the value for summing value at index 0 and index 2 in a is 4

推荐答案

indices索引后可以直接使用sum:

You can use sum directly after indexing with indices:

a = np.array([1,2,3,4])
indices = [0, 2] 
a[indices].sum()

这篇关于Python numpy数组对某些索引求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆