python - 如何查找 Pandas 中组总数的百分比

标签 python performance pandas numpy pandas-groupby

我想找到 pandas 数据框中每个值在其组中所占的百分比。

代码如下,但由于将 lambda 函数传递给转换方法,速度很慢。

有没有办法加快速度?

import pandas as pd

index = pd.MultiIndex.from_product([('a', 'b'), ('alpha', 'beta'), ('hello', 'world')], names=['i0', 'i1', 'i2'])

df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8], [1, 2], [3, 4], [5, 6], [7, 8]], index=index, columns=['A', 'B'])
print(df)

sumto = lambda x: x/x.sum()
result = df['A'].groupby(level=['i0', 'i1']).transform(sumto)
print(result)

输出:

                A  B
i0 i1    i2         
a  alpha hello  1  2
         world  3  4
   beta  hello  5  6
         world  7  8
b  alpha hello  1  2
         world  3  4
   beta  hello  5  6
         world  7  8
i0  i1     i2   
a   alpha  hello    0.250000
           world    0.750000
    beta   hello    0.416667
           world    0.583333
b   alpha  hello    0.250000
           world    0.750000
    beta   hello    0.416667
           world    0.583333
Name: A, dtype: float64

最佳答案

选项 1

df.A.unstack().pipe(lambda d: d.div(d.sum(1), 0)).stack()

i0  i1     i2   
a   alpha  hello    0.250000
           world    0.750000
    beta   hello    0.416667
           world    0.583333
b   alpha  hello    0.250000
           world    0.750000
    beta   hello    0.416667
           world    0.583333
dtype: float64

选项 2

df.A / df.groupby(['i0', 'i1']).A.transform('sum')

i0  i1     i2   
a   alpha  hello    0.250000
           world    0.750000
    beta   hello    0.416667
           world    0.583333
b   alpha  hello    0.250000
           world    0.750000
    beta   hello    0.416667
           world    0.583333
Name: A, dtype: float64

选项 3

f, u = pd.factorize([t[:2] for t in df.index.values])
df.A / np.bincount(f, df.A)[f]

i0  i1     i2   
a   alpha  hello    0.250000
           world    0.750000
    beta   hello    0.416667
           world    0.583333
b   alpha  hello    0.250000
           world    0.750000
    beta   hello    0.416667
           world    0.583333
Name: A, dtype: float64

关于python - 如何查找 Pandas 中组总数的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49581695/

相关文章:

python - 通过 bool 索引数组进行 Numpy 数组赋值

Python:为什么这些代码行显示不同的值?

python - Pycharm **kwargs 自动完成

python - django 发送和接收电子邮件?

c# - 同一进程中线程之间的低延迟通信

python - 如何交换 Dataframe 中的特定列值?

python - 具有广播功能的 numpy 数组构造

c++ - 访问未初始化的值会导致性能下降吗?

c++ - 为什么将可视化调试器附加到我的程序比直接从 visual studio 运行它更快?

python - 查找列中特定字符串的出现次数