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

基于行号的条件指示器:为DataFrame添加master_ind列

解决方案

问题说明

给现有DataFrame新增一列master_ind:仅当ind_2首次取值为1的行,master_ind设为1,其余行全部设为0。

原始数据

行号ind_1ind_2ind_3
1000
2010
3100
4011

期望输出

行号ind_1ind_2ind_3master_ind
10000
20101
31000
40110

实现代码

import pandas as pd

# 构造原始数据
df = pd.DataFrame({
    '行号': [1, 2, 3, 4],
    'ind_1': [0, 0, 1, 0],
    'ind_2': [0, 1, 0, 1],
    'ind_3': [0, 0, 0, 1]
})

# 定位ind_2首次为1的行索引
first_target_row = df[df['ind_2'] == 1].index[0]

# 新增并设置master_ind列
df['master_ind'] = 0
df.loc[first_target_row, 'master_ind'] = 1

print(df)

代码解释

  • df[df['ind_2'] == 1].index[0]:筛选出ind_2值为1的所有行,取第一个匹配行的索引
  • 先将master_ind列全部初始化为0,再通过loc精准定位到目标行修改为1,确保只有首次出现的符合条件行被标记

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:10:54