我可以将 pandas.dataframe.isin() 与数字公差参数一起使用吗?
Can I use pandas.dataframe.isin() with a numeric tolerance parameter?
我事先查看了以下帖子。有没有办法将 DataFrame.isin() 与近似因子或公差值一起使用?或者还有其他方法可以吗?
Filter dataframe rows if value in column is in a set list of values
use a list of values to select rows from a pandas dataframe
EX)
df = DataFrame({'A' : [5,6,3.3,4], 'B' : [1,2,3.2, 5]})
In : df
Out:
A B
0 5 1
1 6 2
2 3.3 3.2
3 4 5
df[df['A'].isin([3, 6], tol=.5)]
In : df
Out:
A B
1 6 2
2 3.3 3.2
你可以用 numpy's isclose 做类似的事情:
df[np.isclose(df['A'].values[:, None], [3, 6], atol=.5).any(axis=1)]
Out:
A B
1 6.0 2.0
2 3.3 3.2
np.isclosereturns这个:
np.isclose(df['A'].values[:, None], [3, 6], atol=.5)
Out:
array([[False, False],
[False, True],
[ True, False],
[False, False]], dtype=bool)
它是 df['A']
的元素和 [3, 6]
的成对比较(这就是为什么我们需要 df['A'].values[: None]
- 用于广播)。由于你要找的是不是接近列表中的任何一个,所以我们在最后调用.any(axis=1)
对于多列,稍微改变切片:
mask = np.isclose(df[['A', 'B']].values[:, :, None], [3, 6], atol=0.5).any(axis=(1, 2))
mask
Out: array([False, True, True, False], dtype=bool)
您可以使用此掩码对 DataFrame 进行切片(即 df[mask]
)
如果您想比较 df['A']
和 df['B']
(以及可能的其他列)与不同的向量,您可以创建两个不同的掩码:
mask1 = np.isclose(df['A'].values[:, None], [1, 2, 3], atol=.5).any(axis=1)
mask2 = np.isclose(df['B'].values[:, None], [4, 5], atol=.5).any(axis=1)
mask3 = ...
然后切片:
df[mask1 & mask2] # or df[mask1 & mask2 & mask3 & ...]
我事先查看了以下帖子。有没有办法将 DataFrame.isin() 与近似因子或公差值一起使用?或者还有其他方法可以吗?
Filter dataframe rows if value in column is in a set list of values
use a list of values to select rows from a pandas dataframe
EX)
df = DataFrame({'A' : [5,6,3.3,4], 'B' : [1,2,3.2, 5]})
In : df
Out:
A B
0 5 1
1 6 2
2 3.3 3.2
3 4 5
df[df['A'].isin([3, 6], tol=.5)]
In : df
Out:
A B
1 6 2
2 3.3 3.2
你可以用 numpy's isclose 做类似的事情:
df[np.isclose(df['A'].values[:, None], [3, 6], atol=.5).any(axis=1)]
Out:
A B
1 6.0 2.0
2 3.3 3.2
np.isclosereturns这个:
np.isclose(df['A'].values[:, None], [3, 6], atol=.5)
Out:
array([[False, False],
[False, True],
[ True, False],
[False, False]], dtype=bool)
它是 df['A']
的元素和 [3, 6]
的成对比较(这就是为什么我们需要 df['A'].values[: None]
- 用于广播)。由于你要找的是不是接近列表中的任何一个,所以我们在最后调用.any(axis=1)
对于多列,稍微改变切片:
mask = np.isclose(df[['A', 'B']].values[:, :, None], [3, 6], atol=0.5).any(axis=(1, 2))
mask
Out: array([False, True, True, False], dtype=bool)
您可以使用此掩码对 DataFrame 进行切片(即 df[mask]
)
如果您想比较 df['A']
和 df['B']
(以及可能的其他列)与不同的向量,您可以创建两个不同的掩码:
mask1 = np.isclose(df['A'].values[:, None], [1, 2, 3], atol=.5).any(axis=1)
mask2 = np.isclose(df['B'].values[:, None], [4, 5], atol=.5).any(axis=1)
mask3 = ...
然后切片:
df[mask1 & mask2] # or df[mask1 & mask2 & mask3 & ...]