0

我不知道如何应用 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'fund': 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'}]

4

1 回答 1

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
于 2013-07-05T10:23:55.010 回答