Pandas eval - 在列上调用用户定义的函数

Pandas eval - call user defined function on columns

正如我的问题所述,我想在 运行 时间调用自定义函数到数据帧。使用自定义函数将计算两个日期(即年龄)之间的差异,将年份转换为月份,从两列中找到最大最小值等。

到目前为止,我成功地执行了算术运算和一些函数,如 abs()、sqrt() 但无法使 min()-max() working.Things 工作,

df.eval('TT = sqrt(Q1)',inplace=True)
df.eval('TT1 = abs(Q1-Q2)',inplace=True)
df.eval('TT2 = (Q1+Q2)*Q3',inplace=True)

以下代码适用于 eval。我怎样才能使用相同的数据框 eval ?

def find_max(x,y):
    return np.maximum(x,y)

eval('max1')(4,7)

def find_age(date_col1,date_col2):
    return 'I know how to calc age but how to call func this with df.eval and assign to new col'

示例数据框:

op_d = {'ID': [1, 2,3],'V':['F','G','H'],'AAA':[0,1,1],'D':['2019/12/04','2019/02/01','2019/01/01'],'DD':['2019-12-01','2016-05-31','2015-02-15'],'CurrentRate':[7.5,2,2],'NoteRate':[2,3,3],'BBB':[0,4,4],'Q1':[2,8,10],'Q2':[3,5,7],'Q3':[5,6,8]}
df = pd.DataFrame(data=op_d)

对 Doc 的任何帮助或 link 表示感谢。

有帮助 link我发现但没有解决我的问题是:

Passing arguments to python eval()

函数可以正常调用,需要用@符号引用:

df                                                                  
   A  B
0  1  0
1  0  0
2  0  1

def my_func(x, y): return x + y                                     

df.eval('@my_func(A, B)')                                          
0    1
1    0
2    1
dtype: int64

当然,这里的期望是你的函数期望系列作为参数。否则,请根据需要将您的函数包装在对 np.vectorize 的调用中。