Seaborn regplot 使用 datetime64 作为 x 轴

Posted

技术标签:

【中文标题】Seaborn regplot 使用 datetime64 作为 x 轴【英文标题】:Seaborn regplot using datetime64 as the x axis 【发布时间】:2017-11-05 09:08:59 【问题描述】:

我有一个如下所示的数据框:

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 可以工作?

【问题讨论】:

【参考方案1】:

Seaborn 不支持 regplot 中的日期时间,但这是一个丑陋的 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,并随着时间的推移增加数字。这假设您有一个定期间隔的时间序列。

【讨论】:

以上是关于Seaborn regplot 使用 datetime64 作为 x 轴的主要内容,如果未能解决你的问题,请参考以下文章