【问题标题】:Pandas, k of n combinations with product sum熊猫,n 个组合中的 k 个与产品总和
【发布时间】:2020-12-17 11:13:41
【问题描述】:

这是我的虚拟 df:

     A    B   C    D    E
0  0.4  0.3  0.5  0.2  0.5
1  0.2  0.6  0.4  0.1  0.8

我想从 5 列中选择 3 列并计算它们的乘积。像第 0 行:A x B x C = 0.06 和 A x B x D = 0.024 等等......有 10 种不同的组合从 5 中挑选 3,我想得到所有产品计算的总和。有没有办法做到这一点 i Pandas?

【问题讨论】:

    标签: pandas combinations


    【解决方案1】:

    对每个系列使用DataFrame.prodrename 的列表理解并通过concat 加入:

    from  itertools import combinations
    
    df1 = pd.concat([df[list(x)].prod(axis=1).rename('_'.join(x)) 
                                     for x in combinations(df.columns, 3)], axis=1)
    print (df1)
       A_B_C  A_B_D  A_B_E  A_C_D  A_C_E  A_D_E  B_C_D  B_C_E  B_D_E  C_D_E
    0  0.060  0.024  0.060  0.040  0.100  0.040  0.030  0.075  0.030  0.050
    1  0.048  0.012  0.096  0.008  0.064  0.016  0.024  0.192  0.048  0.032
    

    编辑:如果想要过滤列名并在列表中指定:

    from  itertools import combinations
    
    cols = ['B','C','D','E']
    df1 = pd.concat([df[list(x)].prod(axis=1).rename('_'.join(x)) 
                                     for x in combinations(cols, 3)], axis=1)
    print (df1)
       B_C_D  B_C_E  B_D_E  C_D_E
    0  0.030  0.075  0.030  0.050
    1  0.024  0.192  0.048  0.032
    

    【讨论】:

    • 如果出于某种原因我只想使用 B、C 和 D 列?
    • @TobiasS - 为可能的列名传递列表添加了解决方案。如果使用 B, C and D 在输出中仅获取 B_C_D 列。
    • @jezrael 谢谢你,非常感谢!
    猜你喜欢
    • 2023-02-22
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 2011-11-10
    • 2013-01-12
    • 2020-03-26
    • 2013-11-18
    • 1970-01-01
    相关资源
    最近更新 更多