python - 将 Pandas 数据帧的每一列与同一数据帧的所有其他列相乘的最有效方法

标签 python pandas dataframe bigdata

假设我有一个类似于以下内容的数据集:

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 列)。实现这一目标最快的方法是什么?

当然,我可以执行嵌套循环或类似的操作来实现此目的,但我希望有一种更有效的方法。

最佳答案

您可以使用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])

关于python - 将 Pandas 数据帧的每一列与同一数据帧的所有其他列相乘的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59673066/

相关文章:

python - 如何将 pandas 中的数据框行排序为从一月到十二月的月份

python - 替换 Pandas 数据框中的行

Python pandas,如何只绘制一个实际有数据点的 DataFrame 并留下间隙

python - 当url包含非英语语言时如何使用pycurl?

python - 我如何从 django 中的 mysql 检索数据并以模式显示,其中我也可以更新它?

Python:从 urllib2.urlopen 调用中获取 HTTP header ?

python - QGraphicsTextItem 的分页 : Confining text to a specific rectangular area

python - 删除 Pandas 数据框列中的多个子字符串

python - Pandas 提高了合并数据帧的效率

python - 将 xml 文件嵌套到 pandas 数据框