【问题标题】:Pandas division of two columns with groupby用 groupby 划分两列的 Pandas
【发布时间】:2017-06-22 03:52:01
【问题描述】:

这显然很简单,但作为熊猫新手,我遇到了困难。

我有一个 CSV 文件,其中包含 3 列,即 State、bene_1_count 和 bene_2_count。

我想计算给定状态下 'bene_1_count' 和 'bene_2_count' 的比率。

df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
           'bene_1_count': [np.random.randint(10000, 99999)
                     for _ in range(12)],
           'bene_2_count': [np.random.randint(10000, 99999)
                     for _ in range(12)]})

我正在尝试以下操作,但它给了我一个错误: '没有要连接的对象'

df['ratio'] = df.groupby(['state']).agg(df['bene_1_count']/df['bene_2_count'])

我无法弄清楚如何“达到” groupby 的状态级别以获取列的比率。

我想要一个状态的列的比率,就像我想要我的输出如下:

    State       ratio

    CA  
    WA  
    CO  
    AZ  

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    另外,声明:您可以创建接受数据框的自定义函数。 groupby 将返回子数据帧。然后,您可以使用 apply 函数将自定义函数应用于每个子数据帧。

    df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
               'bene_1_count': [np.random.randint(10000, 99999)
                         for _ in range(12)],
               'bene_2_count': [np.random.randint(10000, 99999)
                         for _ in range(12)]})
    
    def divide_two_cols(df_sub):
        return df_sub['bene_1_count'].sum() / float(df_sub['bene_2_count'].sum())
    
    df.groupby('state').apply(divide_two_cols)
    

    现在假设您希望将每一行除以每组的总和(例如 AZ 的总和),并保留所有原始列。只需调整上述函数(更改计算并返回整个子数据帧):

    def divide_two_cols(df_sub):
        df_sub['divs'] = df_sub['bene_1_count'] / float(df_sub['bene_2_count'].sum())
        return df_sub
    
    df.groupby('state').apply(divide_two_cols)
    

    【讨论】:

      【解决方案2】:

      我相信您首先需要做的是在找到比率之前按州对计数求和。您可以使用apply访问df中的其他列,然后将它们存储在字典中以映射到原始数据帧中的相应状态。

      import pandas as pd
      import numpy as np
      df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
                  'bene_1_count': [np.random.randint(10000, 99999)
                            for _ in range(12)],
                  'bene_2_count': [np.random.randint(10000, 99999)
                            for _ in range(12)]})
      
      ratios = df.groupby('state').apply(lambda x: x['bene_1_count'].sum() /
                                         x['bene_2_count'].sum().astype(float)).to_dict()
      
      df['ratio'] = df['state'].map(ratios)
      

      【讨论】:

      • 谢谢..它正在工作......但它返回一个系列类型,但我想将计算的比率附加到数据框的列,如 df['ratio']..
      • 我更新了我的帖子以将比率添加回原始数据框。这是您要寻找的结果吗?
      猜你喜欢
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      相关资源
      最近更新 更多