将函数elementwise应用于两个数据帧

2024-10-01 13:27:40 发布

您现在位置:Python中文网/ 问答频道 /正文

如何应用来自相同大小的DataFrameX和{}的函数z_ij = f(x_ij, y_ij),并将结果保存到DataFrameZ?在


Tags: 函数ijdataframexdataframez
1条回答
网友
1楼 · 发布于 2024-10-01 13:27:40

这取决于你有什么样的函数,很多函数已经被矢量化为数据帧,比如+-*/等,所以对于这些函数,你可以简单地做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

相关问题 更多 >