【问题标题】:How to groupby and calculate new field with python pandas?如何使用 python pandas 分组和计算新字段?
【发布时间】:2021-10-24 22:40:50
【问题描述】:

我想按名为“水果”的数据框中的特定列进行分组,并计算该特定水果“好”的百分比

下面是我的初始数据框

import pandas as pd
df = pd.DataFrame({'Fruit': ['Apple','Apple','Banana'], 'Condition': ['Good','Bad','Good']})

数据框

    Fruit   Condition
0   Apple   Good
1   Apple   Bad
2   Banana  Good

下面是我想要的输出数据框

    Fruit   Percentage
0   Apple   50%
1   Banana  100%

注意:因为有 1 个“好”苹果和 1 个“坏”苹果,所以好苹果的百分比是 50%。

请参阅下面我的尝试覆盖所有列

groupedDF = df.groupby('Fruit')
groupedDF.apply(lambda x: x[(x['Condition'] == 'Good')].count()/x.count())

请参阅下面的结果表,该表似乎在计算百分比,但在现有列而不是新列中:

        Fruit Condition
Fruit       
Apple   0.5 0.5
Banana  1.0 1.0

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    我们可以将Conditioneq 进行比较,并利用True 为(1) 和False 在处理为数字时为(0) 的事实,并将groupby meanFruits 相比较:

    new_df = (
        df['Condition'].eq('Good').groupby(df['Fruit']).mean().reset_index()
    )
    

    new_df:

        Fruit  Condition
    0   Apple        0.5
    1  Banana        1.0
    

    我们可以进一步 map 到一个格式字符串和 rename 以得到输出到显示的所需输出:

    new_df = (
        df['Condition'].eq('Good')
            .groupby(df['Fruit']).mean()
            .map('{:.0%}'.format)  # Change to Percent Format
            .rename('Percentage')  # Rename Column to Percentage
            .reset_index()  # Restore RangeIndex and make Fruit a Column
    )
    

    new_df:

        Fruit Percentage
    0   Apple        50%
    1  Banana       100%
    

    *当然也可以进行进一步的操作。

    【讨论】:

      猜你喜欢
      • 2013-03-31
      • 1970-01-01
      • 2020-11-17
      • 2017-12-08
      • 2010-09-27
      • 2014-06-17
      • 1970-01-01
      • 2018-07-24
      • 2017-12-08
      相关资源
      最近更新 更多