gpt4 book ai didi

python - Pandas 中数据帧的自定义计算函数

转载 作者:行者123 更新时间:2023-12-01 03:00:31 24 4
gpt4 key购买 nike

我有两个数据框:

df0

     a  b 
c 0 6
d 0 9

df1

     a  b
c 3 2
d 0 0

我有一个自定义除法函数:

def cdiv(x,y):
if x == 0:
return 0
return x / y

我期望的结果:

     a  b
c 0 3
d 0 Inf

我如何为这两个数据框应用该函数?

最佳答案

您需要divmask :

df = df1.div(df2).mask(df1 == 0, 0)
print (df)
a b
c 0.0 3.000000
d 0.0 inf

或者也许可以用作 ayhan commented如果 DataFrames 中没有 NaN 值:

(df0/df1).fillna(0)

另一个解决方案 numpy.where :

df = pd.DataFrame(np.where(df1 == 0, 0, df1 / df2), index=df1.index, columns=df1.columns)
print (df)
a b
c 0.0 3.000000
d 0.0 inf

关于python - Pandas 中数据帧的自定义计算函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43890744/

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