本文介绍了使用多个isin子句的 pandas 索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我想一次对多个列进行即时测试,则可以执行以下操作:
If I want to do is-in testing on multiple columns at once, I can do:
>>> from pandas import DataFrame
>>> df = DataFrame({'A': [1, 2, 3], 'B': [1, 4, 7], 'C' : [10, 12, 18]})
>>> mask = df[['A','B']].isin({'A': [1, 3], 'B': [4, 7, 12]}).all(axis=1)
>>> df = df[mask]
可行-是否有更简洁的解决方案?
That works--is there a more succinct solution?
推荐答案
TBH,您当前的方法对我来说还不错;我看不到使用isin
或filter
进行改进的方法,因为我看不到如何让isin
仅使用字典中的列或filter
来充当all
TBH, your current approach looks fine to me; I can't see a way with isin
or filter
to improve it, because I can't see how to get isin
to use only the columns in the dictionary or filter
to behave as an all
.
但是,我不喜欢对列名进行硬编码,所以我可能将其写为
I don't like hardcoding column names, though, so I'd probably write this as
>>> keep = {'A': [1, 3], 'B': [4, 7, 12]}
>>> df[df[list(keep)].isin(keep).all(axis=1)]
A B C
2 3 7 18
,或者如果需要需要使用.loc
.
or with .loc
if I needed a handle.
这篇关于使用多个isin子句的 pandas 索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!