如何在大Pandas中找到群体总数的百分比

2024-04-25 01:49:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找出每个值在数据帧中所占的百分比。你知道吗

代码如下,但由于将lambda函数传递给transform方法,因此速度较慢。你知道吗

有没有办法加快速度?你知道吗

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

Tags: lambdaalphahellodfworldindextransformresult
1条回答
网友
1楼 · 发布于 2024-04-25 01:49:20

选项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

相关问题 更多 >