2017-06-04 55 views
6

我有一個數據幀看起來像這樣regplot:Seaborn使用datetime64爲x軸

date   score 
2017-06-04 90 
2017-06-03 80 
2017-06-02 70 

當我嘗試這樣做:

sns.regplot(x=date, y=score, data=df) 

我得到了一個錯誤:

TypeError: reduction operation 'mean' not allowed for this dtype 

日期的dtype爲datetime64[ns],int64分數列。

如何隱藏date列以便regplot可以正常工作?

+0

隨意投票接受的答案! – piRSquared

回答

4

Seaborn不支持日期時間在regplot但這裏是一個醜陋的黑客:

df = df.sort_values('date') 
df['date_f'] = pd.factorize(df['date'])[0] + 1 
mapping = dict(zip(df['date_f'], df['date'].dt.date)) 

ax = sns.regplot('date_f', 'score', data=df) 
labels = pd.Series(ax.get_xticks()).map(mapping).fillna('') 
ax.set_xticklabels(labels) 

產生

enter image description here

這是時間序列迴歸所使用的主要方法。如果您有每日數據,則將第1天的代碼設置爲1,並隨着時間的推移增加數量。這假定你有一個有規律間隔的時間序列。