Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

python - Seaborn regplot using datetime64 as the x axis

I have a dataframe looks like this:

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

When I tried this:

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

I got an error:

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

The dtype for date is datetime64[ns], and int64 for the score column.

How can I covert the date column so that regplot will work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

produces

enter image description here

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...