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

如何用Pandas将DataFrame中所有True值替换为对应行首列值

解决Pandas DataFrame中True值替换为对应行首列值的问题

构造示例数据

先还原你提供的原始DataFrame:

import pandas as pd

df = pd.DataFrame({
    'column1': ['ABC', 'DEF', 'GHI', 'JKL', 'MNO'],
    'column2': [True, 0, 0, True, 0],
    'column3': [0, 0, True, 0, True],
    'column4': [True, 0, 0, 0, True]
})

高效替换方法

不需要指定具体列位置,直接对所有非首列进行批量处理,用mask方法即可实现需求:

# 筛选出需要处理的列(排除首列column1)
target_cols = df.columns[1:]
# 当列中值为True时,替换为对应行的column1值
df[target_cols] = df[target_cols].mask(df[target_cols] == True, df['column1'], axis=0)

结果验证

处理后DataFrame的输出与你期望的一致:

column1column2column3column4
ABCABC0ABC
DEF000
GHI0GHI0
JKLJKL00
MNO0MNOMNO

补充说明

  • mask方法的逻辑是:当第一个参数的布尔条件为True时,用第二个参数的值替换原数据;axis=0确保按行匹配对应首列的值,避免列维度不匹配的问题。
  • 如果你习惯用循环处理,也可以用布尔索引实现,代码如下:
target_cols = df.columns[1:]
for col in target_cols:
    df.loc[df[col] == True, col] = df.loc[df[col] == True, 'column1']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:35:14