将功能元素应用于两个DataFrame [英] Apply a function element-wise to two DataFrames
本文介绍了将功能元素应用于两个DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从相同大小的DataFrame X
和Y
应用函数z_ij = f(x_ij, y_ij)
并将结果保存到DataFrame Z
?
How to apply a function z_ij = f(x_ij, y_ij)
from DataFrame X
and Y
of the same size and save the result to DataFrame Z
?
推荐答案
这取决于您具有哪种功能,已经针对数据帧将许多功能矢量化了,例如+-*/
等,因此对于这些功能,您只需执行Z = X + Y
或Z = X - Y
等.
It depends on what kind of function you have, a lot of functions have already been vectorized for data frame, such as +-*/
etc, so for these functions, you can simply do Z = X + Y
or Z = X - Y
etc.
对于更通用的功能,可以使用numpy.vectorize
对其进行矢量化处理,然后应用于两个数据帧:
For a more general function, you can use numpy.vectorize
to make a vectorized version of it and then apply to two data frames:
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
这篇关于将功能元素应用于两个DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文