pandas 根据月份绘制熊猫数据帧
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43682672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Plot pandas DataFrame against month
提问by blokeley
I need to create a bar plot of the frequency of rows, grouped by month.
我需要创建一个按月分组的行频率条形图。
The problem is that the horizontal axis is not a correct time axis: it misses the months in which there are no data so it is not a continuous time axis.
问题是横轴不是一个正确的时间轴:它错过了没有数据的月份,所以它不是一个连续的时间轴。
Example code:
示例代码:
%matplotlib inline
import pandas as pd
d = {'model': 'ep',
'date': ('2017-02-02', '2017-02-04', '2017-03-01')}
df1 = pd.DataFrame(d)
d = {'model': 'rs',
'date': ('2017-01-12', '2017-01-04', '2017-05-01')}
df2 = pd.DataFrame(d)
df = pd.concat([df1, df2])
# Create a column containing the month
df['month'] = pd.to_datetime(df['date']).dt.to_period('M')
# Group by the month and plot
df.groupby('month')['model'].count().plot.bar();
The resulting bar chart is missing the month 2017-04.
生成的条形图缺少 2017-04 月份。
How can pandas be made to plot all months, even those with no data?
如何让大Pandas绘制所有月份,即使是没有数据的月份?
采纳答案by blokeley
For the record, I used this code:
为了记录,我使用了这个代码:
%matplotlib inline
import pandas as pd
d = {'model': 'ep',
'date': ('2017-02-02', '2017-02-04', '2017-03-01')}
df1 = pd.DataFrame(d)
d = {'model': 'rs',
'date': ('2017-01-12', '2017-01-04', '2017-05-01')}
df2 = pd.DataFrame(d)
df = pd.concat([df1, df2])
# Create a column containing the month
df['month'] = pd.to_datetime(df['date']).dt.to_period('M')
# Get the start and end months
months = df['month'].sort_values()
start_month = months.iloc[0]
end_month = months.iloc[-1]
index = pd.PeriodIndex(start=start_month, end=end_month)
df.groupby('month')['model'].count().reindex(index).plot.bar();
Which gives this plot:
这给出了这个情节:
Thanks to EdChum
感谢 EdChum
回答by EdChum
You can reindex
and pass a constructed PeriodIndex
to achieve this:
您可以reindex
并通过一个构造PeriodIndex
来实现这一点:
df.groupby('month')['model'].count().reindex(pd.PeriodIndex(start=df['month'].sort_values().iloc[0], periods=5)).plot.bar()
For some reason reindex
loses the index name, you can restore this:
由于某种原因reindex
丢失了索引名称,您可以恢复它:
gp = df.groupby('month')['model'].count()
gp = gp.reindex(pd.PeriodIndex(start=df['month'].sort_values().iloc[0], periods=5))
gp.index.name = 'month'
gp.plot.bar()
to get the plot:
得到情节: