pandas 能画出日期的直方图吗? [英] Can Pandas plot a histogram of dates?
问题描述
我已经选择了Series,并将其强制为dtype = datetime64[ns]
的datetime列(尽管仅需要日分辨率...不确定如何更改).
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屋!