[英]Count values in column. Python pandas dataframe
1.I want to count how many males and females are in my "sex" column in excel. 1.我想数一数excel中我的“性别”一栏有多少男多少女。
I tried sex_value = df.groupby("sex").size()
but there are space in some of them in. eg.我试过sex_value = df.groupby("sex").size()
但其中一些有空间。例如。 "F "
and "F"
(the same is with "M" "M "
) "F "
和"F"
(与"M" "M "
相同)
If everything were like "M" or "F"
I would use:如果一切都像"M" or "F"
,我会使用:
sex_value = df.groupby("sex").size()
Output:
sex
F 37
F 27
M 40
M 31
dtype: int64
In my case it should be something like就我而言,它应该是这样的
sex_value_female = df[(df['sex']=='F') & (df['sex'] == 'F ')].sum()
sex_value_male = df[(df['sex']=='M') & (df['sex'] == 'M ')].sum()
but it doesnt work.但它不起作用。
2. The same problem is with mean value. 2.同样的问题是平均值。
#mean value of brainweight and bodyweight for males and females
mean = df.groupby('sex').agg({'bodywt': 'mean', 'brainwt': 'mean'})
Output:
bodywt brainwt
sex
F 19.696216 410.059459
F 21.262963 440.122222
M 21.669750 410.030000
M 22.870968 433.709677
let's do strip to get ride of whitespace让我们做 strip 来摆脱空白
df.sex = df.sex.str.strip()
sex_value = df.groupby("sex").size()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.