我的数据框如下:
现在,我想将x除以y值而不给我一个例外。例如,当我将3除以2时,应该给我1.5;当我将3除以0时,应该给我零。为此,我编写了一个异常函数
def divide(x,y):
try:
result = x/y
print (result)
except ZeroDivisionError:
print (0)
我现在想在数据框中创建一个新列并应用此功能。到目前为止,我已经使用过:
df['num'] = df.apply(divide)
但是,这并没有给我所需的结果。有人可以帮忙吗
答案 0 :(得分:2)
您也可以尝试:
def divide(df):
if(df['y']!=0):
return df['x']/df['y']
else:
return 0
df['num']=df.apply(divide,axis=1)
但是我建议改用这个:
import numpy as np
df['num']=df['x']/df['y']
df.replace(np.inf,0)
答案 1 :(得分:1)
尝试一下:
如果您使用的是python 2.7,则返回x / float(y)
import math
def divide(x,y):
# if you check type(y) or type(x) you will get type: numpy.float64
# pandas internally converts it to a numpy.float64
# when you do division on such values you will get inf as output
# you can check if values are not zero and do calculations or convert it to float like: x / float(y)
if y and not math.isnan(y):
return x/y
df['num'] = df.apply(lambda row: divide(row["x"], row["y"]), axis=1)
答案 2 :(得分:0)
您需要return
的东西,而不是print
的东西,因此它不仅显示,而且还存储在内存中:
def divide(x,y):
try:
return x/y
except ZeroDivisionError:
return 0
df['num'] = df.apply(lambda x: divide(x["x"], x["y"]), axis=1)