Python中如何通过索引数组替换二维数组对应位置的数值
Numpy基于索引数组批量替换二维数组指定位置值
我们需要根据给定的索引数组,将二维数组A中对应索引位置的数值统一替换为0。
原始数据
原始二维数组A:
A = [ [0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 1.98019867, 1.96039735, 1.90331502, 1.81546888, 1.70634771, 0. ], [0. , 2. , 1.98019867, 1.92311635, 1.83527021, 1.72614904, 0. ], [0. , 1.98019867, 1.96039735, 1.90331502, 1.81546888, 1.70634771, 0. ], [0. , 1.92311635, 1.90331502, 1.84623269, 1.75838656, 1.64926538, 0. ], [0. , 1.83527021, 1.81546888, 1.75838656, 1.67054042, 1.56141925, 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. ] ]
索引数组,每一行的两个值分别对应目标位置的行、列索引:
index = [ [1, 2], [2, 4], [3, 4], [3, 5], [4, 2], [5, 2], [5, 5] ]
待替换的目标值:
zero = 0
实现方案
Python原生列表实现
# 拷贝原始数组避免修改原数据 modified_A = [row.copy() for row in A] # 遍历索引数组批量替换 for row_idx, col_idx in index: modified_A[row_idx][col_idx] = zero
Numpy实现(效率更高)
import numpy as np # 转换为numpy数组 A_np = np.array(A) index_np = np.array(index) # 高级索引批量赋值 A_np[index_np[:, 0], index_np[:, 1]] = zero # 如需转回原生列表可调用tolist() modified_A = A_np.tolist()
输出结果
替换后的modified_A如下:
modified_A = [ [0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 1.98019867, 1.96039735, 1.90331502, 1.81546888, 1.70634771, 0. ], [0. , 2. , 1.98019867, 1.92311635, 0. , 1.72614904, 0. ], [0. , 1.98019867, 1.96039735, 1.90331502, 0. , 0. , 0. ], [0. , 1.92311635, 0. , 1.84623269, 1.75838656, 1.64926538, 0. ], [0. , 1.83527021, 0. , 1.75838656, 1.67054042, 0. , 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. ] ]
内容的提问来源于stack exchange,提问作者Farzan Bahmani
相关产品推荐
相关产品推荐

