使用datetime64作为x轴的Seaborn regplot [英] Seaborn regplot using datetime64 as the x axis
本文介绍了使用datetime64作为x轴的Seaborn regplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的数据框:
I have a dataframe looks like this:
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
.
The dtype for date is datetime64[ns]
, and int64
for the score column.
如何隐藏date
列,以使regplot
起作用?
How can I covert the date
column so that regplot
will work?
推荐答案
Seaborn不支持regplot
中的日期时间,但这是一个丑陋的骇客:
Seaborn doesn't support datetimes in regplot
but here's an ugly hack:
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)
产生
这是时间序列回归中使用的主要方法.如果您有每日数据,则将第1天编码为1,并随着日期的增加而增加数字.假设您有一个规则间隔的时间序列.
This is the main approach used in time-series regression. If you have daily data, you code day 1 as 1 and increase the number as the days go by. This assumes you have a regularly-spaced time series.
这篇关于使用datetime64作为x轴的Seaborn regplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文