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

2024-10-04 11:30:58 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个数据帧dfas

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

r是指AB的比值,除了第三行这样的情况。但是,如你们所见,第一行的这个比率已经四舍五入了。你知道吗

如果我跑了

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

因为太圆了,我一行也没赶上。很明显,我可以用除法构造列,将它四舍五入,然后进行比较,但是有没有一种方法可以直接从上面的选择说明中进行比较?你知道吗


Tags: 数据方法df情况比率比值dfas太圆
1条回答
网友
1楼 · 发布于 2024-10-04 11:30:58

我将使用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.

相关问题 更多 >