本文介绍了 pandas :浮点数的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里遇到了一个奇怪的问题.我有一个数据框df
,如下所示:
I've ran into a weird issue here. I have a dataframe df
like below:
In [1561]: df
Out[1561]:
A B
0 16.3 1.10
1 23.2 1.33
2 10.7 -0.43
3 5.7 -2.01
4 5.4 -1.86
5 23.5 3.14
我正在比较列A
的每两个相邻行,并将差异存储在新列中:
I'm comparing every two adjacent rows of column A
and storing the difference in a new column:
In [1562]: df['new_diff'] = (df.A - df.A.shift(-1)).fillna(0)
In [1563]: df
Out[1563]:
A B new_diff
0 16.3 1.10 -6.9
1 23.2 1.33 12.5
2 10.7 -0.43 5.0
3 5.7 -2.01 0.3
4 5.4 -1.86 -18.1
5 23.5 3.14 0.0
当我进行检查以找出new_diff
是5.0
的行时,我得到一个空的数据框.但是,当我在< 5.0
或> 5.0
上进行检查时,它可以正常工作.见下文:
When I do a check to find out rows where new_diff
is 5.0
, I get an empty dataframe. But, it works fine when I do a check on < 5.0
or > 5.0
. See below:
In [1567]: df[df['new_diff'] == 5.0]
Out[1567]:
Empty DataFrame
Columns: [A, B, new_diff]
Index: []
In [1568]: df[df['new_diff'] > 5.0]
Out[1568]:
A B new_diff
1 23.2 1.33 12.5
In [1569]: df[df['new_diff'] < 5.0]
Out[1569]:
A B new_diff
0 16.3 1.10 -6.9
2 10.7 -0.43 5.0
3 5.7 -2.01 0.3
4 5.4 -1.86 -18.1
5 23.5 3.14 0.0
请让我知道我在这里想念什么?
Please let me know what am I missing here?
推荐答案
问题具有浮点精度,需要 numpy.isclose
:
Problem is with float precision, need numpy.isclose
:
print (df['new_diff'].tolist())
[-6.899999999999999, 12.5, 4.999999999999999, 0.2999999999999998, -18.1, 0.0]
print (df[np.isclose(df['new_diff'], 5)])
A B new_diff
2 10.7 -0.43 5.0
这篇关于 pandas :浮点数的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!