我想找到 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/