我想找出每个值在数据帧中所占的百分比。你知道吗
代码如下,但由于将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
选项1
选项2
选项3
相关问题 更多 >
编程相关推荐