gpt4 book ai didi

python - 绘制条形图和 Groupby 关键字

转载 作者:太空宇宙 更新时间:2023-11-03 14:02:49 24 4
gpt4 key购买 nike

我有一个类似于以下内容的 pandas 数据框:

Hospital                           2009-10  2010-11
Llandudno General Hospital 43 54
Dolgellau District Hospital 57 58
Deeside Community Hospital 120 140
Haverfordwest Mental Health Unit 34 30

我想按关键字“心理健康”、“地区”制作不同类型医院的条形图。将所有“精神健康”医院分组在一起,将所有“地区”医院分组在一起等等。

这是迄今为止我的代码:

bedsByType = df[ ['Hospital', '2009-10', '2010-11'] ].groupby(['Mental Health', 'General' , 'Community','District'])

summedAndSortedBedsByType = bedsByType.sum().sort_values( '2009-10')

summedAndSortedBedsByType.plot.barh(figsize=(25,15), title='Different Types of Hospitals')

最佳答案

您的问题中并没有真正指定您如何确定您的组。我假设存在类别列表。然后你可以创建你的图表,如下所示:

import pandas as pd
from matplotlib import pyplot as plt

#sample df

Hospital 2009-10 2010-11
0 Llandudno General Hospital 43 54
1 Dolgellau District Hospital 57 58
2 Deeside Community Hospital 120 140
3 Haverfordwest Mental Health Unit 34 30
4 Morelake General Mental Health Clinic 37 39
5 Manderlay Mental Health Hospital 17 29
6 Cumbria Community Hospital 28 25
7 Mayfair Hospital 17 19
8 New Kent District Hospital 14 17
#define categories in a list
groups = ["Mental Health", "General", "Community", "District"]
#create pattern for grouping
pattern = "|".join(groups)
#create new column with categories, if nothing applies use a fill value
df["type"] = df["Hospital"].str.extract("({})".format(pattern), expand = False).fillna("N/A")
#sum bed numbers for each category
df1 = df.groupby("type")["2009-10", "2010-11"].sum()
#create bar chart
df1.plot.barh(title = "Beds by hospital type")
plt.show()

输出: enter image description here

关于python - 绘制条形图和 Groupby 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49133637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com