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

如何防止pandas resample后aggregate操作丢弃全空列?

pandas重采样时保留全空列的实现方法

问题复现

执行以下时间序列重采样代码时,全为空值的B列会被自动丢弃:

import pandas as pd
df = pd.DataFrame(
    data = {'A': [1, 1, 2], 'B': [None, None, None]},
    index = pd.DatetimeIndex([
        '1990-01-01 00:00:00',
        '1990-01-01 12:00:00',
        '1990-01-02 12:00:00'
    ])
)
print(df.resample('1d').aggregate('mean'))

实际输出:

A
1990-01-01  1.0
1990-01-02  2.0

原因

pandas聚合计算默认开启numeric_only=True配置,会自动排除全为缺失值、无法计算数值统计结果的列。

解决方法

在聚合方法中传入numeric_only=False参数,即可强制保留所有列,全空列的聚合结果会默认返回NaN:

print(df.resample('1d').aggregate('mean', numeric_only=False))

运行输出:

A   B
1990-01-01  1.0 NaN
1990-01-02  2.0 NaN

如果需要B列空值显示为None,可以在重采样后将B列转为object类型:

res_df = df.resample('1d').aggregate('mean', numeric_only=False)
res_df['B'] = res_df['B'].astype(object)
print(res_df)

输出效果符合预期:

A     B
1990-01-01  1.0  None
1990-01-02  2.0  None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 12:48:19