GroupBy 使时间索引消失

GroupBy makes time index disappear

使用这个 DataFrame:

import pandas as pd
df = pd.DataFrame([[1,1],[1,2],[1,3],[1,5],[1,7],[1,9]], index=pd.date_range('2015-01-01', periods=6), columns=['a', 'b'])

            a  b
2015-01-01  1  1
2015-01-02  1  2
2015-01-03  1  3
2015-01-04  1  5
2015-01-05  1  7
2015-01-06  1  9

使用 df = df.groupby(df.b // 4).last() 的事实使日期时间索引消失。为什么?

   a  b
b      
0  1  3
1  1  7
2  1  9

预期结果:

            a  b
2015-01-03  1  3
2015-01-05  1  7
2015-01-06  1  9        

对于 groupby,您的索引总是从分组值中获取。对于你的情况,你可以使用 reset_index 然后 set_index:

df['c'] = df.b // 4
result = df.reset_index().groupby('c').last().set_index('index')

In [349]: result
Out[349]: 
            a  b
index           
2015-01-03  1  3
2015-01-05  1  7
2015-01-06  1  9