pandas Groupby:创建两列的Groupby时,如何按正确的顺序对工作日进行排序?

Pandas groupby: How to sort weekdays in the correct order when creating groupby with two columns?( pandas Groupby:创建两列的Groupby时,如何按正确的顺序对工作日进行排序?)
本文介绍了 pandas Groupby:创建两列的Groupby时,如何按正确的顺序对工作日进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下数据框包含一年中每小时的值(千瓦时)。

cons2016.head()

    Date        Hour    kWh     Month   Weekday
0   2016-01-01  00:00   71.48   January Friday
1   2016-01-01  01:00   65.32   January Friday
2   2016-01-01  02:00   65.38   January Friday
3   2016-01-01  03:00   62.44   January Friday
4   2016-01-01  04:00   57.56   January Friday

我要根据此数据帧(按垂直轴上的工作日和水平轴上的小时数的正确顺序)创建一个Seborn热图。所以我分组:

weekdayhour = cons2016.groupby(["Weekday", "Hour"]).mean()
weekdayhour = weekdayhour.reset_index()
weekdayhour.head()

    Weekday Hour    kWh
0   Friday  00:00   61.188113
1   Friday  01:00   57.231698
2   Friday  02:00   55.818679
3   Friday  03:00   55.074151
4   Friday  04:00   55.049811

但现在工作日按字母顺序(也在热图中):

heat_weekdayhour = weekdayhour.pivot(index="Weekday", columns="Hour", values="kWh")
sns.heatmap(heat_weekdayhour)

我如何才能按正常顺序安排工作日,从星期一到星期日?我尝试按如下方式添加.reindex:

weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
weekdayhour = cons2016.groupby(["Weekday", "Hour"]).mean().reindex(labels=weekdays)

但这给了我TypeError: Expected tuple, got str

感谢您的帮助!

推荐答案

使用Categorical

weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
weekdayhour.Weekday = pd.Categorical(weekdayhour.Weekday,categories=weekdays)
weekdayhour = weekdayhour.sort_values('Weekday')
  Weekday   Hour    kWh
0  Friday  00:00  71.48
1  Friday  01:00  65.32
2  Friday  02:00  65.38
3  Friday  03:00  62.44
4  Friday  04:00  57.56

更多信息:

weekdayhour.Weekday
0    Friday
1    Friday
2    Friday
3    Friday
4    Friday
Name: Weekday, dtype: category
Categories (7, object): [Monday < Tuesday < Wednesday < Thursday < Friday < Saturday < Sunday]

这篇关于 pandas Groupby:创建两列的Groupby时,如何按正确的顺序对工作日进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
Is there any way to quot;extractquot; the dtype conversion functionality from pandas read_csv?(有没有办法从 pandas Read_CSV中提取数据类型转换功能?)
Highlighting rows based on a condition(根据条件突出显示行)
How to downcast numeric columns in Pandas?(如何在 pandas 中向下转换数字列?)
Sort quot;Datequot; in Multi-Index(在多索引中排序日期(Q))
How to prevent groupby from surclassing index?(如何防止Groupby超越指数?)