我想实现一个类似于 DataFrame.corr()
的东西它可以将函数应用于成对列。
例如。
我有一个功能:
def func(x, y):
pass
我要申请
func
到 a_pd
中两列的每个组合(Pandas.DataFrame
的类型)。我想出了一个方法,创建一个新函数 wap_func
包装func
: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)
虽然问题似乎解决了,但并不方便。如果可以像
a_pd.corr()
, 它可以更好。
最佳答案
您是否考虑过使用 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
稍微不同地定义您的函数,以便您可以更无缝地使用 apply
def func(xy):
x, y = xy
return x+y
使用
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
关于python - 将函数应用于 Pandas.DataFrame 中两列的每个组合的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39823587/