将函数应用于 Pandas.DataFrame 中两列的每个组合的更好方法

QM.*_*.py 5 python function apply pandas

我想实现一个类似DataFrame.corr()可以将函数应用于成对列的东西。例如。我有一个功能:

def func(x, y):
    pass
Run Code Online (Sandbox Code Playgroud)

我想应用于(类型)func中两列的每个组合。我找到了一种方法,通过创建一个新函数来包装:a_pdPandas.DataFramewap_funcfunc

def wap_func(x):
    for i in range(len(x)):
        for j in range(i+1, len(x)):
            func(x[i], x[j])

res = a_pd.apply(wap_func, axis=1)
Run Code Online (Sandbox Code Playgroud)

虽然问题似乎解决了,但是不太方便。如果能像这样的话a_pd.corr()就更好了。

Ben*_*njw 2

您考虑过使用该itertools.combinations模块吗?

import pandas as pd
from itertools import combinations

df = pd.DataFrame([[1,2,3], [2,3,4], [3,5,7]], columns = ['A', 'B', 'C'])
print(df)

   A  B  C
0  1  2  3
1  2  3  4
2  3  5  7
Run Code Online (Sandbox Code Playgroud)

稍微不同地定义您的函数,以便您可以更无缝地使用 apply

def func(xy):
    x, y = xy
    return x+y
Run Code Online (Sandbox Code Playgroud)

使用该itertools.combinations模块获取您想要的列的所有组合,依次遍历每个组合,并应用之前定义的函数

for combi in combinations(df.columns, 2):
    df['_'.join([i for i in combi])] = df[[i for i in combi]].apply(func, axis=1, result_type='expand').transpose().values

print(df)

   A  B  C  A_B  A_C  B_C
0  1  2  3    3    4    5
1  2  3  4    5    6    7
2  3  5  7    8   10   12
Run Code Online (Sandbox Code Playgroud)