在大熊猫中使用groupby以获得比例的更有效方法

时间:2019-11-19 09:13:26

标签: python pandas

我有以下熊猫DataFrame:

import pandas as pd

i1 = ["AA", "AA", "AA", "BB", "BB", "BB"]
i2 = ["B1", "B1", "B1", "A1", "A1", "A1"]
col1 = [1, 1, 1, 0, 1, 0]
col2 = [0, 0, 0, 1, 1, 0]
col3 = [1, 1, 0, 0, 0, 0]

df = pd.DataFrame({"I1": i1,
                  "I2": i2,
                  "Col_1":col1,
                  "Col_2":col2,
                  "Col_3":col3})

我想做的是获取每一列i1和i2的比例为1(一个)。例如,I1=AAI2=B1的值应为Col_1=1,Col_2=0, Col_3=0.66

我使用以下代码获取所需的输出:

df.groupby(["I1", "I2"])[["Col_1", "Col_2", "Col_3"]].sum()/df.groupby(["I1", "I2"])[["Col_1", "Col_2", "Col_3"]].count()

但是,我认为这不是最好的方法。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

如果只有mean1值,请使用0,因为mean的定义是sum / count

#mean of all numeric columns (without I1, I2)
df1 = df.groupby(["I1", "I2"]).mean()
#if need specify columns names
#df1 = df.groupby(["I1", "I2"])["Col_1", "Col_2", "Col_3"].mean()
print (df1)
          Col_1     Col_2     Col_3
I1 I2                              
AA B1  1.000000  0.000000  0.666667
BB A1  0.333333  0.666667  0.000000