首页 > 解决方案 > 熊猫:resample.apply 丢弃索引名称

问题描述

出于某种原因,df.resample("M").apply(foo)将索引名称放在df. 这是预期的行为吗?

import pandas as pd
df = pd.DataFrame({"a": np.arange(60)}, index=pd.date_range(start="2018-01-01", periods=60))
df.index.name = "dte"
df.head()
#            a
#dte          
#2018-01-01  0
#2018-01-02  1
#2018-01-03  2
#2018-01-04  3
#2018-01-05  4
def f(x):
    print(x.head())

df.resample("M").apply(f)
#2018-01-01    0
#2018-01-02    1
#2018-01-03    2
#2018-01-04    3
#2018-01-05    4
#Name: a, dtype: int64

更新/澄清: 当我说删除名称时,我的意思是函数接收到的系列没有与其索引关联的名称组件

标签: pythonpython-3.xpandas

解决方案


我建议使用resample- groupbywith的替代方法Grouper

def f(x):
    print(x.head())

df.groupby(pd.Grouper(freq="M")).apply(f)
dte          
2018-01-01  0
2018-01-02  1
2018-01-03  2
2018-01-04  3
2018-01-05  4
            a
dte          
2018-01-01  0
2018-01-02  1
2018-01-03  2
2018-01-04  3
2018-01-05  4
             a
dte           
2018-02-01  31
2018-02-02  32
2018-02-03  33
2018-02-04  34
2018-02-05  35

推荐阅读