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

Pandas DataFrame中仅col3与上一行相同时比较col1值的实现问题

解决方案

你只需要新增当前行col3与上一行col3相等的判断条件,和原有col1的对比条件做逻辑与即可,或者更优雅的是按col3分组后在组内执行对比逻辑,天然避免跨组对比,两种实现如下:

方法1:直接追加跨组过滤条件

在原有逻辑基础上,增加df['col3'].eq(df['col3'].shift())的判断,两个条件同时成立时col2才为True:

import pandas as pd
data1 = {'col1': [10, 30, 11, 24, 22, 50, 12, 10, 30, 31, 32, 33, 20, 41, 44], 'col3': [
    'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AC', 'AC']}
df = pd.DataFrame(data1, columns=['col1', 'col3'])

# 新增col3相等的判断条件,和原有条件做逻辑与
df['col2'] = df['col1'].gt(df['col1'].mul(2).shift()) & df['col3'].eq(df['col3'].shift())
print(df)

方法2:按col3分组后组内执行对比(更推荐)

针对col3的每个分组单独做shift操作,每个分组的第一行shift结果为NaN,对比结果自动为False,不需要额外写过滤逻辑:

import pandas as pd
data1 = {'col1': [10, 30, 11, 24, 22, 50, 12, 10, 30, 31, 32, 33, 20, 41, 44], 'col3': [
    'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AB', 'AC', 'AC']}
df = pd.DataFrame(data1, columns=['col1', 'col3'])

# 按col3分组,组内计算对比逻辑
df['col2'] = df['col1'].gt(df.groupby('col3')['col1'].transform(lambda x: x.mul(2).shift()))
print(df)

运行结果(两种方法输出一致)

col1 col3   col2
0     10   AB  False
1     30   AB   True
2     11   AB  False
3     24   AB   True
4     22   AB  False
5     50   AB   True
6     12   AB  False
7     10   AB  False
8     30   AB   True
9     31   AB  False
10    32   AB  False
11    33   AB  False
12    20   AB  False
13    41   AC  False
14    44   AC  False

可以看到索引13行的col2已经变为预期的False,不再发生跨组无效对比。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:39:03