2024-10-04 11:30:58 发布
网友
假设我有一个数据帧dfas
df
A B r 145 146 99.32 1 10 10 2 20 35
列r是指A与B的比值,除了第三行这样的情况。但是,如你们所见,第一行的这个比率已经四舍五入了。你知道吗
r
A
B
如果我跑了
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 : floatThe relative tolerance parameter (see Notes).atol : floatThe absolute tolerance parameter (see Notes).equal_nan : boolWhether 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.
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.
我将使用np.isclose()方法:
它非常灵活-可以指定相对或绝对公差:
相关问题 更多 >
编程相关推荐