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

Python按组获取变更前值并新增列的实现方案咨询

pandas按组提取值变更的前一个值

核心思路:按Group分组后,先获取每组内的前一行值,再仅保留当前值与前一行值不同的那些前值,其余置空。

实现步骤

  • 按Group分组,对Value列调用shift(1),得到每组内每行的前一行值
  • 使用where方法过滤:仅当当前行Value和前一行Value不相等时,保留shift后的结果,否则设为NaN
  • 将处理结果赋值给新列Previous_Value,若需要空字符串替代NaN,可额外用fillna('')处理

完整代码

import pandas as pd
import numpy as np

# 构造样本数据集
data = {
    'Group': ['01', '01', '01', '02', '02', '02', '03', '03', '03', '03'],
    'Value': [10, 10, 10, 5, 5, 15, 20, 25, 15, 15]
}
df = pd.DataFrame(data)

# 生成Previous_Value列
df['Previous_Value'] = df.groupby('Group')['Value'].shift(1).where(df['Value'] != df.groupby('Group')['Value'].shift(1))

# 可选:将NaN替换为空字符串,匹配期望输出格式
df['Previous_Value'] = df['Previous_Value'].fillna('')

# 查看结果
print(df)

输出结果

Group  Value Previous_Value
0    01     10               
1    01     10               
2    01     10               
3    02      5               
4    02      5               
5    02     15              5
6    03     20               
7    03     25             20
8    03     15             25
9    03     15               

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:38:12