Python 如何应用于_datetime或使用sort_索引,以便对日期进行排序?
我不知道如何应用于_datetime,因为日期的输出没有排序Python 如何应用于_datetime或使用sort_索引,以便对日期进行排序?,python,datetime,pandas,Python,Datetime,Pandas,我不知道如何应用于_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 下面是我的代码
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
下面是我的代码,最后一行已经用于\u datetime with format,我尝试了排序\u 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文件链接,请查收:
数据样本如下所示:
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'}]在索引(转换为)日期之后,您必须:
to_datetime不需要任何排序。那么,df.index=pd的哪一部分to_datetime(df.index,格式=“%d/%m/%Y”)不正确,输出日期没有排序?
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