【问题标题】:Manipulate A Group Column in Pandas在 Pandas 中操作组列
【发布时间】:2015-05-06 02:01:43
【问题描述】:

我有一个包含 Dist、Class 和 Count 列的数据集。

我想按 dist 对该数据集进行分组,并将每组的计数列除以该组的计数总和(将其标准化为 1)。

以下 MWE 展示了我迄今为止的方法。但我想知道:有没有更紧凑/流行的方式来写这个?

import pandas as pd
import numpy as np

a = np.random.randint(0,4,(10,3))
s = pd.DataFrame(a,columns=['Dist','Class','Count'])

def manipcolumn(x):
    csum = x['Count'].sum()
    x['Count'] = x['Count'].apply(lambda x: x/csum)
    return x

s.groupby('Dist').apply(manipcolumn)

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    获取标准化“计数”列的另一种方法是使用groupbytransform 获取每个组的总和,然后将返回的系列除以“计数”列。您可以将此系列重新分配回您的 DataFrame:

    s['Count'] = s['Count'] / s.groupby('Dist')['Count'].transform(np.sum)
    

    这避免了对定制 Python 函数的需要和apply 的使用。对您问题中的小示例 DataFrame 进行测试表明它快了大约 8 倍。

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      相关资源
      最近更新 更多