如何将数据框中的分隔日期与日期时间相结合
问题描述:
我有一个数据框,日期(日,月,年)有三列。 我想将这三列组合到一个日期列以备后用。 我想使用日期列来引用和绘制matplotlib轴。 如何将数据框中的分隔日期与日期时间相结合
我想这对于(lambda x:'%s %2s %2s' % (x['year'],x['month'], x['day']),axis=1)
创建新列和使用,但所以我用matplotlib.dates.datestr2num()
但却它不工作要么它会创建一个字符串。
问题总结
如何将这些三列中数据帧都datetime和 matplotlib使用结合起来?
答
您可以使用to_datetime
与子day
,month
,year
:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
df = pd.DataFrame({'day':[1,2,3,4,3,4,5],
'month':[4,5,7,4,5,6,8],
'year':[2013,2013,2103,2013,2013,2103,2013],
'A':[1,3,5,5,6,7,9],
'B':[4,5,6,5,4,3,4]})
#print (df)
#convert to datetime
df['date'] = pd.to_datetime(df[['day','month','year']])
print (df)
A B day month year date
0 1 4 1 4 2013 2013-04-01
1 3 5 2 5 2013 2013-05-02
2 5 6 3 7 2103 2103-07-03
3 5 5 4 4 2013 2013-04-04
4 6 4 3 5 2013 2013-05-03
5 7 3 4 6 2103 2103-06-04
6 9 4 5 8 2013 2013-08-05
#remove columns
df.drop(['day','month','year'], axis=1, inplace=True)
#set index from date dolumn - datetimeindex
df.set_index('date', inplace=True)
print (df)
A B
date
2013-04-01 1 4
2013-05-02 3 5
2103-07-03 5 6
2013-04-04 5 5
2013-05-03 6 4
2103-06-04 7 3
2013-08-05 9 4
#plot and set format of axis x:
ax = df.plot()
ticklabels = df.index.strftime('%Y-%m-%d')
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
plt.show()
答
使用字符串:
import datetime
datetime.datetime.strptime('<date string>', '%d%m%Y').date()
我没有,但我得到:ValueError异常:无法组装日期时间:每月超出月份 – samanv
您的熊猫版本是什么? 'pd.show_versions()'? – jezrael
pandas version --- pandas:0.19.1 – samanv