Python GroupBy使时间索引消失
使用此数据帧:Python GroupBy使时间索引消失,python,pandas,time-series,Python,Pandas,Time Series,使用此数据帧: 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']) i、 e 使用df=df.groupby(df.b//4).last()会使日期时间索引消失。为什么? a b b 0 1 3 1 1 7 2 1 9 预期结果
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'])
i、 e
使用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
您的索引总是从分组值中获取。对于您的情况,您可以使用重置索引
,然后设置索引
:
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
不知道你为什么会这样,你实际上是在这里生成一个新的df和索引,如果你的索引是['a','b','c','d','e','f'],同样的事情也会发生@EdChum I编辑并编写了预期的结果。
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