熊猫将3个数据帧逐个元素地迭代为一个函数

时间:2018-12-10 18:20:45

标签: pandas dataframe

我写道:

def revertcheck(basevalue,first,second):
    if basevalue==1:
        return 0 
    elif basevalue > first and first > second:
        return -abs(first-second)
    elif basevalue < first and first < second:
        return -abs(first-second)
    else:
        return abs(first-second)

现在我有3个相同大小的类型的相关矩阵

pandas.core.frame.DataFrame

我想遍历每个元素,并将所有这三个值一次输入到我的函数中。有人可以提示我该怎么做吗?

AAPL    AMZN    BAC GE  GM  GOOG    GS  SNP XOM
AAPL    1.000000    0.567053    0.410656    0.232328    0.562110    0.616592    0.800797    -0.139989   0.147852
AMZN    0.567053    1.000000    -0.012830   0.071066    0.271695    0.715317    0.146355    -0.861710   -0.015936
BAC 0.410656    -0.012830   1.000000    0.953016    0.958784    0.680979    0.843638    0.466912    0.942582
GE  0.232328    0.071066    0.953016    1.000000    0.935008    0.741110    0.667574    0.308813    0.995237
GM  0.562110    0.271695    0.958784    0.935008    1.000000    0.857678    0.857719    0.206432    0.899904
GOOG    0.616592    0.715317    0.680979    0.741110    0.857678    1.000000    0.632255    -0.326059   0.675568
GS  0.800797    0.146355    0.843638    0.667574    0.857719    0.632255    1.000000    0.373738    0.623147
SNP -0.139989   -0.861710   0.466912    0.308813    0.206432    -0.326059   0.373738    1.000000    0.369004
XOM 0.147852    -0.015936   0.942582    0.995237    0.899904    0.675568    0.623147    0.369004    1.000000

1 个答案:

答案 0 :(得分:1)

假设basevaluefirstsecond是您的三个大小和结构完全相同的数据帧,那么您可以按照矢量化的方式进行操作:

output = abs(first - second)
output = output.mask(basevalue == 1, 0)
output = output.mask((basevalue > first) & (first > second), -abs(first - second))
output = output.mask((basevalue < first) & (first < second), -abs(first - second))