如何从下面列出的数据框中绘制直方图?我想根据Education
专栏将每个教育级别的女性人数可视化。
示例从下面打印我们的输出:
高中学历中的女性30
大学中的
女性33本科中的女性14
我尝试了什么
#show max rows and columns
pd.set_option('display.max_rows', 1000)
countFemales = myDataFrame['Gender'].str.contains("Female").sum()
#subset myDataFrame based on Gender's value, returns boolean series
isFemale = myDataFrame['Gender']=='Female'
#fileter dataframe based on boolean condition, extract female column as df
femaleDataframe = myDataFrame[isFemale]
# extract only unique values from female data: Bachelor, Colleage, High Scool..
femaleLevelOfEducation = femaleDataframe.Education.unique()
print("women in High Scool " + str(femaleDataframe["Education"].str.contains("High School or Below").sum()))
print("women in College " + str(femaleDataframe["Education"].str.contains("College").sum()))
print("women in Bachelor " + str(femaleDataframe["Education"].str.contains("Bachelor").sum()))
femaleDataframe.plot(x=femalLevelOfEducation, y=countFemales, kind='hist')
plt.show() //this is where I am stuck
编辑
如果这样做plt.bar(x=femaleLevelOfEducation, y=countFemales, height=60)
,我将得到如下所示的条形图。但是,这对我来说没有意义,因为根据打印说明,数据集中有:高中女生30
名大学女生30名
学士14
所以现在的问题是,为什么y轴拉伸到140,而不是最大拉伸到33?
数据集:https://drive.google.com/file/d/1Y8VdU1Y7jGR17vWDspm31PdL-d1BQlDg/view?usp = sharing
由于sum()的计算,您得到的计数不正确。但是,对于您提到的问题,groupby()
可能是最好的解决方案。
见下文:
import pandas as pd
df = pd.DataFrame({
'gender':['F', 'F', 'F', 'M', 'F', 'F', 'F'],
'edu':['Bachelor', 'Masters','Bachelor','Bachelor','HighSchool','Doctor','Doctor'],
'age':[30,30,31,28,25,29,33]
})
# df.groupby(['Gender','Edu']).size().unstack().plot(kind='bar')
df[df['gender']=='F'].groupby(['gender', 'edu']).size().unstack().plot(kind='bar')
使用的数据框:
gender edu age
0 F Bachelor 30
1 F Masters 30
2 F Bachelor 31
3 M Bachelor 28
4 F HighSchool 25
5 F Doctor 29
6 F Doctor 33
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句