小智 9
以防万一有人像我一样发现自己在这里,现在有一个函数可以为 pandas 执行此操作!
Z = X.combine(Y, lambda x, y: f(x, y))
Run Code Online (Sandbox Code Playgroud)
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.combine.html
这取决于你,很多功能已经矢量化什么样的功能,用于数据帧,如+-*/等,所以对于这些功能,你可以简单地做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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
565 次 |
| 最近记录: |