熊猫:浮点数的差异

时间:2018-12-04 06:59:49

标签: python python-3.x pandas

我在这里遇到了一个奇怪的问题。我有一个数据框df,如下所示:

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的每两相邻行,并将差异存储在新列中:

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_diff5.0的行时,我得到一个空的数据框。但是,当我对< 5.0> 5.0进行检查时,它工作正常。见下文:

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

请让我知道我在这里想念什么?

3 个答案:

答案 0 :(得分:1)

问题具有浮点精度,需要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

答案 1 :(得分:1)

只需致电round

df[df['new_diff'].round() == 5.0]

      A     B  new_diff
2  10.7 -0.43       5.0

答案 2 :(得分:0)

或者,在过滤过程中使字符串类型为'new_diff'(不修改实际数据),然后检查其是否等于'5.0'

print(df[df['new_diff'].astype(str)=='5.0'])

输出:

      A     B  new_diff
2  10.7 -0.43       5.0