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

如何在Pandas中按用户分组后用shift获取下月label值?

解决方案

要实现每个用户下月的label值且避免跨组取值,直接按cust_id分组后对label列执行shift(-1)即可,每组最后一行会自动填充为NaN。

完整代码

import pandas as pd

# 初始化原数据
df = pd.DataFrame({
    'cust_id': [1,1,1,1,1,1,2,2,2,2,2],
    'period': [200010,200011,200012,200101,200102,200103,200010,200011,200012,200101,200103],
    'volume': [1,2,3,4,5,6,7,8,9,10,12],
    'num_transactions': [3,4,5,6,7,8,9,10,11,12,13],
    'label': [1,1,1,0,1,1,0,0,0,0,0]
})

# 生成next_month_label列
df['next_month_label'] = df.groupby('cust_id')['label'].shift(-1)

print(df)

代码说明

  • groupby('cust_id'):将数据按客户ID拆分,确保每个客户的时序数据单独处理,不会跨组混淆。
  • shift(-1):对每组内的label列执行向上偏移操作,当前行取值为下一行的label;每组最后一行没有后续数据,自动填充为NaN,完全符合需求。

输出结果与期望一致:

cust_id  period  volume  num_transactions  label  next_month_label
0         1  200010       1                 3      1               1.0
1         1  200011       2                 4      1               1.0
2         1  200012       3                 5      1               0.0
3         1  200101       4                 6      0               1.0
4         1  200102       5                 7      1               1.0
5         1  200103       6                 8      1               NaN
6         2  200010       7                 9      0               0.0
7         2  200011       8                10      0               0.0
8         2  200012       9                11      0               0.0
9         2  200101      10                12      0               0.0
10        2  200103      12                13      0               NaN

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 16:06:31