Python 尝试使用str.contains和boolean掩码,但仅用于Pandas中的单个值
我很难想出一个好的解决方案来隔离具有相同唯一ID的行,这些行只包含特定值的实例,而如果它们包含任何其他值,则删除具有共享唯一ID的所有行。(如果不清楚,很抱歉,但我有下面的示例df) 这是我对str.contains和布尔掩码的逻辑,我正在考虑使用类似的东西 df[df['ID'].isin(df.loc[df1.Yurrr.str.contains('Bodega'),'ID'].unique())] 示例df:Python 尝试使用str.contains和boolean掩码,但仅用于Pandas中的单个值,python,pandas,Python,Pandas,我很难想出一个好的解决方案来隔离具有相同唯一ID的行,这些行只包含特定值的实例,而如果它们包含任何其他值,则删除具有共享唯一ID的所有行。(如果不清楚,很抱歉,但我有下面的示例df) 这是我对str.contains和布尔掩码的逻辑,我正在考虑使用类似的东西 df[df['ID'].isin(df.loc[df1.Yurrr.str.contains('Bodega'),'ID'].unique())] 示例df: ID % Yurrr abc123 0.8
ID % Yurrr
abc123 0.833 Bodega
abc123 0.87 Bodega
abc123 0.867 Bodega
abc123 0.812 Bodega
lmn789 0.837 Beck's
lmn789 0.856 Chopped Cheese
lmn789 0.813 Bodega
lmn789 0.812 Beck's
xyz456 0.111 Cardi B
xyz456 0.222 Cardi B
xyz456 0.333 Bodega
xyz456 0.444 Bodega
输出df:
ID % Yurrr
abc123 0.833 Bodega
abc123 0.87 Bodega
abc123 0.867 Bodega
abc123 0.812 Bodega
您可以使用以下选项:
df[df.groupby('ID')['Yurrr'].transform(lambda x: x.str.contains('Bodega').all())]
或
输出:
ID % Yurrr
0 abc123 0.833 Bodega
1 abc123 0.870 Bodega
2 abc123 0.867 Bodega
3 abc123 0.812 Bodega
@柯克兰肖蒂,不客气。快乐编码!你能帮我解决这个问题吗?
ID % Yurrr
0 abc123 0.833 Bodega
1 abc123 0.870 Bodega
2 abc123 0.867 Bodega
3 abc123 0.812 Bodega