我尝试排序后,pandas行被移位了

时间:2017-06-08 15:22:49

标签: python python-3.x pandas dataframe

我有这个数据帧,其头部如下所示:

Out[8]:
        Date    Value
0   2016-06-30  481100.0
1   2016-05-31  493800.0
2   2015-12-31  514000.0
3   2015-10-31  510700.0

我想使用Dates列作为索引,然后根据日期的顺序对行进行排序。

当我尝试根据第一列对其进行排序时使用:

df.set_index('Date', inplace=True)
然后头部看起来像这样:

            Value
Date    
2016-06-30  481100.0
2016-05-31  493800.0
2015-12-31  514000.0
2015-10-31  510700.0

不仅没有根据日期对数据框进行排序,标题也搞砸了:enter image description here

为什么会发生这种情况,我该如何纠正呢?

1 个答案:

答案 0 :(得分:2)

您应该使用sort_values

In [3]: df
Out[3]: 
         Date     Value
0  2016-06-30  481100.0
1  2016-05-31  493800.0
2  2015-12-31  514000.0
3  2015-10-31  510700.0

In [4]: df = df.sort_values(by='Date')

In [5]: df
Out[5]: 
         Date     Value
3  2015-10-31  510700.0
2  2015-12-31  514000.0
1  2016-05-31  493800.0
0  2016-06-30  481100.0

编辑: 排序后,您可以将所需的列设置为数据帧的索引:

In [6]: df.set_index('Date', inplace=True)

In [7]: df
Out[7]: 
               Value
Date                
2015-10-31  510700.0
2015-12-31  514000.0
2016-05-31  493800.0
2016-06-30  481100.0