【问题标题】:Python. Pandas. CSV. Count mean by other column valuePython。熊猫。 CSV。按其他列值计算平均值
【发布时间】:2018-06-23 09:06:44
【问题描述】:

我有下表:

Days, Age,  Sex

5,    39,   F

4,    54,   M

4,    26,   M

5,    42,   M

4,    29,   M

我想计算 2 组的平均天数:35 岁以下和 36 岁以上。我在考虑类似的事情

df["Days"].mean().where(df["Age"]>35)......

我看到结果的最佳方式是:

Age
Age <= 35   4
Age >= 35   4.6666

最好的命令是什么?谢谢。

【问题讨论】:

    标签: python pandas csv dataframe pandas-groupby


    【解决方案1】:

    用途:

    df = (df['Days'].groupby(df["Age"]>35)
                    .mean()
                    .rename(index={True:'Age > 35', False:'Age <= 35'})
                    .reset_index())
    

    或者:

    df["Age"] = np.where(df["Age"]>35,'Age > 35','Age <= 35')
    df = df.groupby('Age', as_index=False)['Days'].mean()
    print (df)
             Age      Days
    0  Age <= 35  4.000000
    1   Age > 35  4.666667
    

    【讨论】:

    • 谢谢。对于第二个建议,我收到此错误:无法使用灵活类型执行 reduce。你能告诉我修复它的方法吗?
    • @Jerry - 似乎有些错误,你使用最新的 pandas/numpy 版本吗? pandas 0.22.0。 ?
    • print (df['Days'].dtype) 是什么?
    • 类型为int64
    • 是的,第二次它返回“无效语法”,然后我在最后添加“)”并返回“无法使用灵活类型执行缩减”
    【解决方案2】:
    df.groupby(pd.cut(df['Age'], bins=[0, 35, np.inf]))['Days'].mean()
    Out: 
    Age
    (0.0, 35.0]    4.000000
    (35.0, inf]    4.666667
    Name: Days, dtype: float64
    

    【讨论】:

    • 它们可以重命名,但我认为这不是问题的关键。
    • 谢谢。我有输出,但对于这两行我都有 NaN 而不是数字。你能告诉我修复它的方法吗?我要检查缺失值吗?
    • 你能发布df[['Age', 'Sex', 'Days']].head().to_dict()的输出吗?
    • 您的 Days 列可能不是数字 @Jerry。
    • {'年龄': {0: 39, 1: 54, 2: 26, 3: 42, 4: 29}, '天数': {0: 5, 1: 4, 2: 4, 3: 5, 4: 4}, 'Sex': {0: 'F', 1: 'M', 2: 'M', 3: 'M', 4: 'M'}}
    猜你喜欢
    • 1970-01-01
    • 2018-11-14
    • 2020-04-09
    • 2022-07-14
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2014-11-04
    • 2015-09-11
    相关资源
    最近更新 更多