python - Pandas 用 groupby 划分两列

标签 python python-3.x pandas

这显然很简单,但作为一个 pandas 新手,我被卡住了。

我有一个包含 3 列的 CSV 文件,即州、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 的状态级别以获取列的比例。

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

    State       ratio

    CA  
    WA  
    CO  
    AZ  

最佳答案

或者,声明:您可以创建接受数据框的自定义函数。 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)

关于python - Pandas 用 groupby 划分两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42046885/

相关文章:

Python Date 两个日期之间的中间值

python - 将html解析为文本并在python中保留链接

python - 获取 FB token Python

python - Pandas 的每日频率计数

python - 使用数组从多重索引中选择值

python - 如何在 Mac OSX Yosemite 上安装 libret?

python - 从 String 中删除一个 char,更有效的方法是什么?

python - Opencv 3.0 - 模块对象没有属性 'xfeatures2d'

python - 编译 gVim 支持 Python 3

python - 是否有 pandas/numpy 函数可以将整数分布到后续的零中?