Seaborn regplot 使用 datetime64 作为 x 轴

Seaborn regplot using datetime64 as the x axis

我的数据框如下所示:

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

日期的数据类型是 datetime64[ns],得分列的数据类型是 int64

如何隐藏 date 列以便 regplot 起作用?

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)

产生

这是时间序列回归中使用的主要方法。如果您有每日数据,则将第 1 天编码为 1,并随着时间的推移增加数字。这假设您有一个固定间隔的时间序列。