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

如何调整Pandas DataFrame 按月末日期整合各列有效数值

实现方法

核心逻辑是先把每条数据映射到它归属的月末日期,再按归属日期分组聚合各列的非空有效值即可,完整代码如下:

import pandas as pd
from numpy import nan

# 构造示例DataFrame
df = pd.DataFrame({'Date': ['2014-09-30', '2014-10-01',
                            '2014-10-31', '2014-11-01'],
                     'X1': [20, nan, 19, nan],
                     'X2': [nan,2,nan,4],
                     'X3': [5,nan,9,nan],
                     }) 

# 1. 将Date列转换为datetime格式
df['Date'] = pd.to_datetime(df['Date'])

# 2. 计算每条数据对应的归属月末:月末日期直接保留,非月末日期(这里都是月初1号)归属到上月月末
df['belong_month_end'] = df['Date'].where(
    df['Date'].dt.is_month_end, 
    df['Date'] - pd.offsets.MonthEnd(1)
)

# 3. 按归属月末分组,聚合各列的非空值
agg_rule = {'Date': ('belong_month_end', 'first')}
# 动态为所有指标列添加聚合规则,不需要手动列每一列
for col in df.columns.difference(['Date', 'belong_month_end']):
    agg_rule[col] = (col, lambda x: x.dropna().iloc[0])

result = df.groupby('belong_month_end', as_index=False).agg(**agg_rule).drop('belong_month_end', axis=1)

运行后输出的result就是你要的结果:

Date  X1  X2  X3
0 2014-09-30  20   2   5
1 2014-10-31  19   4   9

如果需要Date列为字符串格式,最后再加一行:
result['Date'] = result['Date'].dt.strftime('%Y-%m-%d')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:15:10