我有两个数据框:
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
我如何为这两个数据框应用该函数?
最佳答案
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/