简体   繁体   中英

pandas: resample.apply discards index names

For some reason doing df.resample("M").apply(foo) drops the index name in df . Is this expected behavior?

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

update/clarification: When I said drops the name I meant that series received by the function doesn't have a name component associated with its index

I suggest use alternative of resample - groupby with 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM