【问题标题】:Count values in column. Python pandas dataframe计算列中的值。 Python 熊猫数据框
【发布时间】:2020-05-11 22:41:22
【问题描述】:

1.我想在excel的“性别”列中统计男性和女性的数量。

我试过sex_value = df.groupby("sex").size(),但其中一些有空间。例如。 "F ""F""M" "M " 也一样)

如果一切都像 "M" or "F" 我会使用:

sex_value = df.groupby("sex").size() 

Output:
sex
F           37
F           27
M           40
M           31
dtype: int64

在我的情况下应该是这样的

sex_value_female = df[(df['sex']=='F') & (df['sex'] == 'F ')].sum()
sex_value_male = df[(df['sex']=='M') & (df['sex'] == 'M ')].sum()

但它不起作用。

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

【问题讨论】:

标签: python python-3.x excel pandas dataframe


【解决方案1】:

让我们剥离以摆脱空白

df.sex = df.sex.str.strip()
sex_value = df.groupby("sex").size() 

【讨论】:

    猜你喜欢
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2019-08-19
    • 1970-01-01
    • 2018-10-26
    • 2021-07-21
    相关资源
    最近更新 更多