Pandas:检查列除法与舍入匹配的行

Pandas: check rows for columns division match with rounding

假设我有一个 DataFrame df as

 A       B    r
145    146    99.32
1      10     10
2      20     35

r 表示 AB 的比率,第三行等情况除外。但是,如您所见,第一行的这个比率已经四舍五入了。

如果我运行

df[df.A/df.B == r]

由于四舍五入,我没有捕捉到任何行。显然我可以用除法构造列,将其四舍五入然后进行比较,但是有没有办法直接从上面的选择指令中执行此操作?

我会使用np.isclose()方法:

In [32]: df
Out[32]:
   A  B          r
0  3  7   0.420000
1  3  7   0.428571
2  1  2  10.000000

In [33]: df.A/df.B
Out[33]:
0    0.428571
1    0.428571
2    0.500000
dtype: float64

In [34]: np.isclose(df.A/df.B, df.r)
Out[34]: array([False,  True, False], dtype=bool)

In [35]: np.isclose(df.A/df.B, df.r, atol=1e-2)
Out[35]: array([ True,  True, False], dtype=bool)

In [36]: df.loc[np.isclose(df.A/df.B, df.r, atol=1e-2)]
Out[36]:
   A  B         r
0  3  7  0.420000
1  3  7  0.428571

In [37]: df.loc[np.isclose(df.A/df.B, df.r)]
Out[37]:
   A  B         r
1  3  7  0.428571

它非常灵活 - 您可以指定相对或绝对公差:

rtol : float

The relative tolerance parameter (see Notes).

atol : float

The absolute tolerance parameter (see Notes).

equal_nan : bool

Whether to compare NaN’s as equal. If True, NaN’s in a will be considered equal to NaN’s in b in the output array.