如何简洁计算排除指定索引位置的2D numpy数组元素和?
更简洁的2D NumPy数组求和(排除指定索引)
最优实现:利用NumPy内置sum方法
只排除单个索引位置的话,最简洁高效的方式是先计算整个数组的总和,再减去指定位置的元素值:
import numpy as np # 示例数组 arr = np.array([[0., 1., 1., 0., 1.], [0., 0., 0., 0., 0.], [1., 8., 1., 0., 1.], [1., 1., 0., 1., 1.], [0., 0., 0., 1., 1.]]) # 指定要排除的索引(行2,列1) exclude_row, exclude_col = 2, 1 # 计算总和并排除指定位置 total = arr.sum() - arr[exclude_row, exclude_col] print(total) # 输出12.0
这种方式的优势:
- 代码极简,可读性强
- 依赖NumPy底层优化的
sum()方法,比Python原生循环快几个数量级,尤其适合大数组
修正你的循环实现(可选)
如果坚持用循环,需要修正原函数的几个问题:参数未传入排除索引、变量名不一致(arr vs base):
def num_order(arr, exclude_x, exclude_y): tot = 0 rows, cols = arr.shape for row in range(rows): for col in range(cols): if row != exclude_x or col != exclude_y: tot += arr[row][col] return tot # 调用示例 print(num_order(arr, 2, 1)) # 输出12.0
内容的提问来源于stack exchange,提问作者dzdws
相关产品推荐
相关产品推荐

