You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:57:04