【问题标题】:Most efficient way to multiply every column of a large pandas dataframe with every other column of the same dataframe将大熊猫数据帧的每一列与同一数据帧的每一列相乘的最有效方法
【发布时间】:2020-01-09 22:31:49
【问题描述】:

假设我有一个看起来像这样的数据集:

INDEX   A   B   C
    1   1   1   0.75
    2   1   1   1
    3   1   0   0.35
    4   0   0   1
    5   1   1   0

我想获得一个如下所示的数据框,其中包含原始列以及列之间所有可能的交互:

INDEX   A   B   C       A_B     A_C     B_C
    1   1   1   0.75    1       0.75    0.75
    2   1   1   1       1       1       1
    3   1   0   0.35    0       0.35    0
    4   0   0   1       0       0       0
    5   1   1   0       1       0       0

我的实际数据集非常大(约 100 列)。实现这一目标的最快方法是什么?

当然,我可以使用嵌套循环或类似方法来实现这一点,但我希望有更有效的方法。

【问题讨论】:

    标签: python pandas dataframe bigdata


    【解决方案1】:

    您可以为此使用itertools.combinations

    >>> import pandas as pd
    >>> from itertools import combinations
    >>> df = pd.DataFrame({
    ...     "A": [1,1,1,0,1],
    ...     "B": [1,1,0,0,1],
    ...     "C": [.75,1,.35,1,0]
    ... })
    >>> df.head()
       A  B     C
    0  1  1  0.75
    1  1  1  1.00
    2  1  0  0.35
    3  0  0  1.00
    4  1  1  0.00
    >>> for col1, col2 in combinations(df.columns, 2):
    ...     df[f"{col1}_{col2}"] = df[col1] * df[col2]
    ...
    >>> df.head()
       A  B     C  A_B   A_C   B_C
    0  1  1  0.75    1  0.75  0.75
    1  1  1  1.00    1  1.00  1.00
    2  1  0  0.35    0  0.35  0.00
    3  0  0  1.00    0  0.00  0.00
    4  1  1  0.00    1  0.00  0.00
    

    如果您需要对可以使用的列对上的任意函数进行矢量化:

    import numpy as np
    
    def fx(x, y):
        return np.multiply(x, y)
    
    for col1, col2 in combinations(df.columns, 2):
        df[f"{col1}_{col2}"] = np.vectorize(fx)(df[col1], df[col2])
    

    【讨论】:

      【解决方案2】:

      我不知道有一个原生的pandas 函数来解决这个问题,但itertools.combinations 将是对嵌套循环的改进。

      你可以这样做:

      from itertools import combinations
      
      df = pd.DataFrame(data={"A": [1,1,1,0,1], 
                              "B": [1,1,0,0,1], 
                              "C": [0.75, 1, 0.35, 1, 0]})
      
      for comb in combinations(df.columns, 2): 
          col_name = comb[0] + "_" + comb[1]
          result[col_name] = df[comb[0]] * df[comb[1]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-18
        • 1970-01-01
        • 2020-05-22
        • 1970-01-01
        • 1970-01-01
        • 2020-11-04
        • 2017-12-08
        相关资源
        最近更新 更多