使用datetime64作为x轴的Seaborn regplot

Che*_*eng 11 python numpy pandas seaborn

我的数据框看起来像这样:

date         score  
2017-06-04    90
2017-06-03    80
2017-06-02    70
Run Code Online (Sandbox Code Playgroud)

当我尝试这个时:

sns.regplot(x=date, y=score, data=df)
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

TypeError: reduction operation 'mean' not allowed for this dtype
Run Code Online (Sandbox Code Playgroud)

日期的dtype是datetime64[ns],int64对于得分列.

如何隐藏date列以便它regplot可以工作?

ayh*_*han 12

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)
Run Code Online (Sandbox Code Playgroud)

产生

在此输入图像描述

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