[英]Use `isin(list1)` in pandas to identify values in a column that has all the items in list1
对于如下所示的给定熊猫数据框,
h1 h2 h3
mn a 1
mn b 1
rs b 1
pq a 1
we c 1
如果我使用isin()
过滤,比如df[df["h2"].isin(["a","b"])]["h1"].unique()
,它会导致以下结果:
h1
mn
rs
pq
我需要找到与列表中所有元素匹配的条目,而不是与列表中的任何元素匹配的行为,即所需的输出应该是:
h1
mn
这究竟是如何实现的? isin()
列表的元素个数是任意的,可以大于 2。
您可以将issubset
与set
per groups 一起用于掩码:
s = df.groupby('h1')['h2'].apply(lambda x: set(["a","b"]).issubset(x))
print (s)
h1
mn True
pq False
rs False
we False
Name: h2, dtype: bool
然后过滤索引值:
vals = s.index[s]
print (vals)
Index(['mn'], dtype='object', name='h1')
new_df = df.groupby('h1').filter(lambda x: np.isin(['a','b'],x['h2']).all())
print(new_df)
h1 h2 h3
0 mn a 1
1 mn b 1
s = df.groupby('h1')['h2'].apply(lambda x: np.isin(['a','b'],x).all())
s.index[s]
#Index(['mn'], dtype='object', name='h1')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.