繁体   English   中英

检查pandas DataFrame列中字符串中是否有字符串

[英]Check if string within strings in pandas DataFrame column

我有一个非常简单的pandas DataFrame,我想选择DataFrame的一部分,该部分包含一个列,其中包含另一个字符串

因此,如果这是我的DataFrame,并且我希望那些包含Loc列中some列的列如何才能完成?

             Loc 
0      'something'  
1      'nothing'  

我尝试了两件事:

df['some' in df['Loc']]
df[df.Loc.contains('some')]

但两种解决方案都无效

您需要使用contains ,一种字符串访问器方法。

>>> df['Loc'].str.contains('some')
0     True
1    False
Name: Loc, dtype: bool

然后,可以对结果使用布尔索引来选择数据帧的相关行。

df[df['Loc'].str.contains('some')]

使用替换,一种有趣的方式

df[df.Loc.replace({'some':np.nan},regex=True).isnull()]
Out[787]: 
           Loc
0  'something'

自Alex在评论中提到它以来的更新

df[df.Loc.apply(lambda x : 'some' in x)]
Out[801]: 
           Loc
0  'something'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM