【发布时间】:2020-11-27 23:35:37
【问题描述】:
我有以下代码,但我希望它按月份而不是总数排序。 日期格式为 YYYY-MM-DD
df.groupby(df['date'].dt.strftime('%B'))['total'].sum().sort_values().plot.bar(figsize=(20,10))
【问题讨论】:
标签: python python-3.x pandas matplotlib
我有以下代码,但我希望它按月份而不是总数排序。 日期格式为 YYYY-MM-DD
df.groupby(df['date'].dt.strftime('%B'))['total'].sum().sort_values().plot.bar(figsize=(20,10))
【问题讨论】:
标签: python python-3.x pandas matplotlib
月份名称是字符串,Python 不知道如何将它们与实际顺序联系起来。你可以试试reindex:
# you need to type this in
months = ['January', 'February', 'March', 'April',
'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December']
(df.groupby(df['date'].dt.strftime('%B'))
['total'].sum()
.reindex(months)
.plot.bar(figsize=(20,10))
)
或者,更不容易出错的是将数字月份与名称一起分组,然后丢弃数字:
(df.groupby([df['date'].dt.month,df['date'].dt.strftime('%B')])
['total'].sum()
.reset_index(level=0)
.plot.bar(figsize=(20,10))
)
【讨论】:
您需要告诉sort_values() 函数您希望它如何执行此操作。尝试用sort_values(by='date')替换这部分表达式
【讨论】:
【讨论】: