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

Python DataFrame中基于条件添加标记列的实现方法

按多条件为DataFrame添加Flag列

原始数据

我们有如下初始DataFrame:

import pandas as pd

df = pd.DataFrame({
    'Class': ['A', 'A', 'A', 'B', 'B'],
    'Player_type': ['forward', 'defence', 'defence', 'forward', 'defence'],
    'Goals': [0, 1, 1, 0, 0],
    'Assists': [1, 0, 1, 0, 0]
})

需要满足的条件

当某一行同时满足以下所有条件时,Flag列标记为1,否则为0:

  • 当前行Class等于下一行的Class
  • 当前行Player_type为forward
  • 下一行Player_type为defence
  • 下一行Assists为0
  • 当前行Goals为0

解决方案

利用Pandas的shift(-1)方法获取下一行的对应字段,再组合所有条件生成Flag列:

# 提取下一行的相关字段
next_class = df['Class'].shift(-1)
next_player_type = df['Player_type'].shift(-1)
next_assists = df['Assists'].shift(-1)

# 组合所有判断条件
conditions = (
    (df['Class'] == next_class) &
    (df['Player_type'] == 'forward') &
    (next_player_type == 'defence') &
    (next_assists == 0) &
    (df['Goals'] == 0)
)

# 生成Flag列,布尔值转整数(True→1,False→0)
df['Flag'] = conditions.astype(int)

最终结果

运行后得到的DataFrame如下:

Class Player_type  Goals  Assists  Flag
0     A      forward      0        1     1
1     A      defence      1        0     0
2     A      defence      1        1     0
3     B      forward      0        0     1
4     B      defence      0        0     0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:01:05