【问题标题】:how to plot dataframe based on count of obervations?如何根据观察次数绘制数据框?
【发布时间】:2020-06-18 16:40:15
【问题描述】:

如何从下面列出的数据框中绘制直方图? 我想根据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 岁的女性
大学 33 中的女性
单身女性 14

那么现在的问题是,为什么 y 轴伸展到 140 而不是最大 33?

数据集:https://drive.google.com/file/d/1Y8VdU1Y7jGR17vWDspm31PdL-d1BQlDg/view?usp=sharing

【问题讨论】:

标签: python-3.x pandas dataframe


【解决方案1】:

由于 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

【讨论】:

  • 实际上,像 OP 一样在布尔数组上使用 sum() 将提供正确数量的女性记录
  • 我同意。只是当您尝试将其用于绘图,而不是获得正确的值时,OP 将得到不正确的结果。
猜你喜欢
  • 1970-01-01
  • 2018-07-05
  • 2018-05-13
  • 2018-04-26
  • 2021-08-15
  • 1970-01-01
  • 2019-05-02
  • 2021-10-17
  • 2019-06-04
相关资源
最近更新 更多