gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:05:58 26 4
gpt4 key购买 nike

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

到目前为止,我成功地执行了算术运算和一些像 abs()、sqrt() 这样的函数,但无法让 min()-max() 工作。工作的是,

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 的链接。

我发现但没有解决我的问题的有用链接是:

Dynamic Expression Evaluation in pandas using pd.eval()

Using local variables with multiple assignments with pandas eval function

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 的调用中,视情况而定。

关于python - Pandas eval - 在列上调用用户定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60620755/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com