【发布时间】:2019-01-21 23:36:55
【问题描述】:
我有以下名为 df 的 pd.DataFrame:
date cluster_label value
0 2018-11-14 02:16:22 0 1.5
1 2018-11-14 02:16:22 0 7.0
2 2018-11-14 02:16:22 0 2.5
3 2018-11-14 02:16:22 1 3.0
4 2018-11-14 02:16:22 1 0.5
5 2018-11-14 02:16:22 2 1.0
在设置多级索引或数据框之前,我执行以下命令将日期列转换为只有月份和年份值:
self.df['date'] = self.df['date'].dt.to_period('M')
self.df.set_index(['cluster_label', 'date'], inplace=True)
现在,输出是这样的:
value
cluster_label date
0 2018-11 1.5
2018-11 7.0
2018-11 2.5
1 2018-11 3.0
2018-11 0.5
2 2018-11 1.0
但这是错误的。我希望输出没有日期列的重复索引。输出应如下所示:
value
cluster_label date
0 2018-11 1.5
7.0
2.5
1 2018-11 3.0
0.5
2 2018-11 1.0
我做错了什么,如何更改我的代码以获得所需的输出?
【问题讨论】:
标签: python pandas dataframe multi-level