2016-11-22 31 views
0

我有一個數據框,日期(日,月,年)有三列。 我想將這三列組合到一個日期列以備後用。 我想使用日期列來引用和繪製matplotlib軸。 enter image description here如何將數據框中的分隔日期與日期時間相結合

我想這對於(lambda x:'%s %2s %2s' % (x['year'],x['month'], x['day']),axis=1)創建新列和使用,但所以我用matplotlib.dates.datestr2num()但卻它不工作要麼它會創建一個字符串。

問題總結

如何將這些三列中數據幀都datetime和 matplotlib使用結合起來?

回答

2

您可以使用to_datetime與子daymonthyear

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() 
+0

我沒有,但我得到:ValueError異常:無法組裝日期時間:每月超出月份 – samanv

+0

您的熊貓版本是什麼? 'pd.show_versions()'? – jezrael

+0

pandas version --- pandas:0.19.1 – samanv

0

使用字符串:

import datetime 
datetime.datetime.strptime('<date string>', '%d%m%Y').date()