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

如何基于行列约束交集与批准矩阵修改Numpy矩阵元素?

Numpy矩阵按条件修改实现方案

完整实现代码

import numpy as np

def change_element_in(wow, pop):
    # 筛选行和为1的行索引
    target_rows = np.where(wow.sum(axis=1) == 1)[0]
    # 筛选全零列的列索引
    target_cols = np.where(wow.sum(axis=0) == 0)[0]
    
    # 遍历目标位置,根据pop矩阵验证后修改
    for row in target_rows:
        for col in target_cols:
            if pop[row, col] == 1:
                wow[row, col] = 1

# 测试用例
wow = np.array([[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1]])

pop = np.array([[1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
                [0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0],
                [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]])

change_element_in(wow, pop)
print(wow)

代码逻辑说明

  1. 定位目标行:通过wow.sum(axis=1)计算每行元素的和,用np.where筛选出和为1的行索引(对应示例中的第2行)。
  2. 定位目标列:通过wow.sum(axis=0)计算每列元素的和,用np.where筛选出全零列的索引(对应示例中的第3、6、7、9、10、11列)。
  3. 验证并修改:遍历所有目标行与列的交叉位置,检查pop矩阵对应位置的值,若为1则将wow对应位置设为1。

运行结果

[[1 0 0 1 0 0 0 0 0 0 0 0]
 [0 1 1 0 0 0 0 0 0 0 1 0]
 [0 0 0 0 0 0 0 1 0 0 0 1]]

内容的提问来源于stack exchange,提问作者PapayaApple

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 01:57:38