我已将x的值检索为x = 10.64589195722904
,需要使用loc在我现有的数据框中进行匹配。由于减法结果可能是负值,我必须忽略它,因此我正在使用math.fabs来实现它。
fdf = df.loc[(math.fabs(df['x'] - x) <= 0.01 & math.fabs(df['x'] - x) >= 0.001)]
但这会引发错误:
TypeError Traceback (most recent call last)
<ipython-input-256-b8a71a5bd17c> in <module>
10 # fdf = df.loc[math.fabs((df['x'] - k) <= 0.001) & (math.fabs(df['x'] - k) >= 0.0001) ]
11
---> 12 df.loc[(math.fabs(df['x'] - x) <= 0.01 & math.fabs(df['x'] - x) >= 0.001)]
13 fdf.head()
~\.conda\envs\pyenv\lib\site-packages\pandas\core\series.py in wrapper(self)
110 if len(self) == 1:
111 return converter(self.iloc[0])
--> 112 raise TypeError(f"cannot convert the series to {converter}")
113
114 wrapper.__name__ = f"__{converter.__name__}__"
TypeError: cannot convert the series to <class 'float'>
答案 0 :(得分:1)
使用numpy.fabs
处理矢量化值,并在掩码周围添加()
,因为优先级运算符:
s = np.fabs(df['x'] - x)
fdf = df[(s <= 0.01) & (s >= 0.001)]
替代方法是使用Series.between
:
fdf = df[np.fabs(df['x'] - x).between(0.01, 0.001)]
答案 1 :(得分:1)