问题描述
我有以下数据框:
actual_credit min_required_credit
0 0.3 0.4
1 0.5 0.2
2 0.4 0.4
3 0.2 0.3
我需要添加一列来指示实际信用> = min_required_credit的位置.结果将是:
I need to add a column indicating where actual_credit >= min_required_credit. The result would be:
actual_credit min_required_credit result
0 0.3 0.4 False
1 0.5 0.2 True
2 0.4 0.4 True
3 0.1 0.3 False
我正在执行以下操作:
df['result'] = abs(df['actual_credit']) >= abs(df['min_required_credit'])
但是,第三行(0.4和0.4)始终导致False.在各个地方研究了此问题后,包括:我仍然无法使它正常工作.只要两列的值相同,则结果为False,这是不正确的.
However the 3rd row (0.4 and 0.4) is constantly resulting in False. After researching this issue at various places including: What is the best way to compare floats for almost-equality in Python? I still can't get this to work. Whenever the two columns have an identical value, the result is False which is not correct.
我正在使用python 3.3
I am using python 3.3
推荐答案
由于不精确的浮点比较,您可以or
与 np.isclose
,isclose
采用相对和绝对公差参数,因此以下各项应能起作用:
Due to imprecise float comparison you can or
your comparison with np.isclose
, isclose
takes a relative and absolute tolerance param so the following should work:
df['result'] = df['actual_credit'].ge(df['min_required_credit']) | np.isclose(df['actual_credit'], df['min_required_credit'])
这篇关于比较 pandas 列中的浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!