如何应用to_datetime或sort_index以便对日期进行排序?

时间:2013-07-05 07:21:33

标签: python datetime pandas

我不知道如何申请to_datetime,因为日期的输出没有排序。

In [16]: df[('JAS','ask')][:6]
Out[16]: 
2013-02-01    118.6400
2013-03-01    123.1600
2012-08-01    104.0200
2012-11-01    108.6600
2013-01-02    114.8800
2013-04-02    125.9700
Name: (JAS, ask), dtype: object

以下是我的代码,最后一行已经使用了to_datetime格式,我尝试了sort_index但结果仍然失败:

import json
import pandas as pd

dat = json.load(open('pruItems.json'))
frames = [] 
keys=[]
for d in dat:
    if d['data']:
        frame = pd.DataFrame.from_records(d['data'], columns=['date', 'bid' ,'ask'])
        frame.set_index('date', inplace=True)
        frames.append(frame)
        keys.append(d['fund'])
df = pd.concat(frames, axis=1, keys=keys)

df.index = pd.to_datetime(df.index, format='%d/%m/%Y')

附上请查找我的json文件的链接: https://docs.google.com/file/d/0B1UY10-kbb4YYU5KYXllOVNYbnc/edit?usp=sharing

数据样本如下:     db = {u'data':[[u'18 / 06/2013',u'34.8400',u'34.8400'],       [u'17 / 06/2013',u'34.4900',u'34.4900']],       u'fund':u'TGC'},     {u'data':[[u'18 / 06/2013',u'14.9179',u'14.9179'],      [u'17 / 06/2013',u'14.8712',u'14.8712']],      你''''u'FEF'},     {u'data':[[u'18 / 06/2013',u'6.6780',u'6.6780'],      [u'17 / 06/2013',u'6.6510',u'6.6570']],      u'fund':u'FAF'}]

1 个答案:

答案 0 :(得分:1)

在索引(转换为)日期之后,您必须sort_index

In [11]: df
Out[11]:
                TGC               FEF              FAF
                bid      ask      bid      ask     bid     ask
date
18/06/2013  34.8400  34.8400  14.9179  14.9179  6.6780  6.6780
17/06/2013  34.4900  34.4900  14.8712  14.8712  6.6510  6.6570

In [12]: df.index = pd.to_datetime(df.index)

In [13]: df
Out[13]:
                TGC               FEF              FAF
                bid      ask      bid      ask     bid     ask
2013-06-18  34.8400  34.8400  14.9179  14.9179  6.6780  6.6780
2013-06-17  34.4900  34.4900  14.8712  14.8712  6.6510  6.6570

In [14]: df.sort_index()  # you can also do this inplace=True
Out[14]:
                TGC               FEF              FAF
                bid      ask      bid      ask     bid     ask
2013-06-17  34.4900  34.4900  14.8712  14.8712  6.6510  6.6570
2013-06-18  34.8400  34.8400  14.9179  14.9179  6.6780  6.6780