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

Pandas基于已有列创建新列,获取各分组每月最后一天的Mark值

不需要自定义函数,使用pandas原生向量化操作即可实现,该方案全程无行级别遍历,性能极高,适配大数据量处理场景,具体实现如下:

实现代码

import pandas as pd

# 构造示例数据
df = pd.DataFrame({
    'Found':['A','A','A','A','A','B','B','B'],
    'Date':['14/10/2021','19/10/2021','29/10/2021','30/09/2021','20/09/2021','20/10/2021','29/10/2021','15/10/2021'],
    'LastDayMonth':['29/10/2021','29/10/2021','29/10/2021','30/09/2021','30/09/2021','29/10/2021','29/10/2021','29/10/2021'],
    'Mark':[1,2,3,4,3,1,2,3]
})

# 1. 转换日期格式,避免字符串匹配出现格式错误
df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
df['LastDayMonth'] = pd.to_datetime(df['LastDayMonth'], dayfirst=True)

# 2. 构造映射关系:(Found, 当月最后一天) 对应 当月最后一天的Mark值
last_day_mark_map = df[df['Date'] == df['LastDayMonth']].set_index(['Found', 'LastDayMonth'])['Mark']

# 3. 映射到原表生成新列
df['Mark_LastDayMonth'] = df.set_index(['Found', 'LastDayMonth']).index.map(last_day_mark_map)

print(df)

输出结果

Found       Date LastDayMonth  Mark  Mark_LastDayMonth
0     A 2021-10-14   2021-10-29     1                  3
1     A 2021-10-19   2021-10-29     2                  3
2     A 2021-10-29   2021-10-29     3                  3
3     A 2021-09-30   2021-09-30     4                  4
4     A 2021-09-20   2021-09-30     3                  4
5     B 2021-10-20   2021-10-29     1                  2
6     B 2021-10-29   2021-10-29     2                  2
7     B 2021-10-15   2021-10-29     3                  2

方案优势

  • 所有操作均为pandas原生向量化实现,无自定义行级别遍历逻辑,性能远高于基于apply的自定义函数方案
  • 时间复杂度为O(n),仅需要一次过滤、两次索引构造、一次映射操作,千万级数据量也可快速处理
  • 兼容所有pandas主流版本,无需额外依赖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:15:04