Python 对两个数据帧应用函数元素

Python 对两个数据帧应用函数元素,python,pandas,Python,Pandas,如何从相同大小的数据帧x和y应用函数z_ij=f(x_ij,y_ij),并将结果保存到数据帧z 这取决于您使用的函数类型,很多函数已经为数据帧进行了矢量化,例如+-*/等,因此对于这些函数,您可以简单地执行Z=X+Y或Z=X-Y等 对于更通用的函数,您可以使用numpy.vectorize生成其矢量化版本,然后应用于两个数据帧: import numpy as np import pandas as pd X = pd.DataFrame([[1,2], [3,4]]) Y = pd.Data

如何从相同大小的数据帧
x
y
应用函数
z_ij=f(x_ij,y_ij)
,并将结果保存到数据帧
z

这取决于您使用的函数类型,很多函数已经为数据帧进行了矢量化,例如
+-*/
等,因此对于这些函数,您可以简单地执行
Z=X+Y
Z=X-Y

对于更通用的函数,您可以使用
numpy.vectorize
生成其矢量化版本,然后应用于两个数据帧:

import numpy as np
import pandas as pd

X = pd.DataFrame([[1,2], [3,4]])
Y = pd.DataFrame([[2,1], [3,3]])
​
def f(x, y):                      # this is a demo function that takes in two ints and 
    return str(x) + str(y)        # concatenate them as str
​
vecF = np.vectorize(f)            # vectorize the function with numpy.vectorize
​
X
#   0   1
#0  1   2
#1  3   4

Y
#   0   1
#0  2   1
#1  3   3

pd.DataFrame(vecF(X, Y))          # apply the function to two data frames

#    0   1
#0  12  21
#1  33  43

万一有人发现自己像我一样在这里,现在有一个功能可以为熊猫做到这一点

Z=X.combine(Y,λX,Y:f(X,Y))

这太美了!最好将其作为pandas函数
pandas.elementwise_组合(left=X,right=Y,func=f)
保留列和索引(假设
X
X
共享相同的索引/列)