根据月份绘制熊猫数据框

Posted

技术标签:

【中文标题】根据月份绘制熊猫数据框【英文标题】:Plot pandas DataFrame against month 【发布时间】:2017-09-26 17:13:55 【问题描述】:

我需要创建一个按月分组的行频条形图。

问题在于横轴不是一个正确的时间轴:它错过了没有数据的月份,所以它不是一个连续的时间轴。

示例代码:

%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();

生成的条形图缺少 2017-04 月份。

如何让 pandas 绘制所有月份,即使是那些没有数据的月份?

【问题讨论】:

【参考方案1】:

为了记录,我使用了这个代码:

%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();

这给出了这个情节:

感谢 EdChum

【讨论】:

【参考方案2】:

您可以reindex 并传递一个构造的PeriodIndex 来实现此目的:

df.groupby('month')['model'].count().reindex(pd.PeriodIndex(start=df['month'].sort_values().iloc[0], periods=5)).plot.bar()

由于某种原因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()

获取剧情:

【讨论】:

以上是关于根据月份绘制熊猫数据框的主要内容,如果未能解决你的问题,请参考以下文章

在一个图中绘制不同的熊猫数据框[重复]

绘制分组的熊猫数据框

如何绘制熊猫数据框的多列

从订单簿绘制热图(熊猫数据框)

散景折线图未绘制完整的熊猫数据框

如何按列绘制数据框的多个字典?蟒蛇熊猫