Pandas 可以绘制日期的直方图吗? [英] Can Pandas plot a histogram of dates?
问题描述
我已经将我的系列强制转换为 dtype=datetime64[ns]
的日期时间列(尽管只需要日期分辨率...不知道如何更改).
I've taken my Series and coerced it to a datetime column of dtype=datetime64[ns]
(though only need day resolution...not sure how to change).
import pandas as pd
df = pd.read_csv('somefile.csv')
column = df['date']
column = pd.to_datetime(column, coerce=True)
但绘图不起作用:
ipdb> column.plot(kind='hist')
*** TypeError: ufunc add cannot use operands with types dtype('<M8[ns]') and dtype('float64')
我想绘制一个仅按周、月或年显示日期计数的直方图.
I'd like to plot a histogram that just shows the count of dates by week, month, or year.
在 pandas
中肯定有办法做到这一点吗?
Surely there is a way to do this in pandas
?
推荐答案
鉴于此 df:
date
0 2001-08-10
1 2002-08-31
2 2003-08-29
3 2006-06-21
4 2002-03-27
5 2003-07-14
6 2004-06-15
7 2003-08-14
8 2003-07-29
而且,如果还不是这样:
and, if it's not already the case:
df["date"] = df["date"].astype("datetime64")
按月显示日期计数:
df.groupby(df["date"].dt.month).count().plot(kind="bar")
.dt
允许您访问日期时间属性.
.dt
allows you to access the datetime properties.
哪个会给你:
您可以按年、日等替换月.
You can replace month by year, day, etc..
例如,如果您想区分年份和月份,只需执行以下操作:
If you want to distinguish year and month for instance, just do:
df.groupby([df["date"].dt.year, df["date"].dt.month]).count().plot(kind="bar")
给出:
这是你想要的吗?清楚了吗?
Was it what you wanted ? Is this clear ?
希望这有帮助!
这篇关于Pandas 可以绘制日期的直方图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!