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

pandas中resample的.apply方法传入对象:Series还是DataFrame?

Pandas中resample.apply的参数类型解析

示例数据

首先定义示例DataFrame:

import pandas as pd
df = pd.DataFrame({'A':range(0,100),'B':range(0,200,2)},index=pd.date_range('1/1/2022',periods=100,freq='D'))

数据预览:

A    B
2022-01-01   0    0
2022-01-02   1    2
2022-01-03   2    4
2022-01-04   3    6
2022-01-05   4    8
...         ..  ...
2022-04-06  95  190
2022-04-07  96  192
2022-04-08  97  194
2022-04-09  98  196
2022-04-10  99  198

核心疑问与解答

核心结论

resample.apply的参数x类型并非固定,核心差异在于是否逐列处理,这也是它和groupby.apply的关键区别(groupby.apply默认总是传递整个分组的DataFrame):

  • 默认行为(多列DataFrame):函数逐列应用到每个时间分组,此时x是对应列的分组内Series。
  • 当函数返回非标量结果(如Series/DataFrame):resample会传递整个分组的完整DataFrame,此时x是分组内的DataFrame。

现象逐一解释

  1. df.resample('M').apply(lambda x: print(type(x)))输出Series
    默认逐列处理逻辑下,每个x对应单个月份分组中某一列的Series,因此打印的类型是pandas.core.series.Series。

  2. df.resample('M').apply(lambda x: type(x))返回DataFrame
    每个分组的每列都会返回Series类型对象,这些结果会被整理成以月份为索引、原列为列名的DataFrame,因此整体返回DataFrame结构。

  3. df.resample('M').apply(lambda x: x.sum(axis=1))报错
    此时x是Series,sum(axis=1)要求按列求和,但Series没有列维度(axis=1无效),因此抛出Series类型无轴1的错误。若要对整个分组的DataFrame按行求和,需让x为分组DataFrame,写法为:

    df.resample('M').apply(lambda grp: grp.sum(axis=1))
    
  4. df.resample('M').apply(lambda x: x.stack())正常运行
    stack()是DataFrame专属方法(Series无此方法),此时resample会传递整个分组的DataFrame给函数,因此stack()可正常执行,最终返回拼接后的MultiIndex Series。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:10:39