微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在其他列中搜索子串的Pandas列

我有一个例子.csv,导入为df.csv,如下所示:

    Ethnicity, Description
  0 french, Irish Dance Company
  1 Italian, Moroccan/Algerian
  2 Danish, Company in Netherlands
  3 Dutch, french
  4 English, Englishfrench
  5 Irish, Irish-American

我想在test1 [‘Ethnicity’]中检查pandas test1 [‘Description’]中的字符串.这应该返回行0,3,4和5,因为描述字符串包含种族列中的字符串.

到目前为止,我已经尝试过:

df[df['Ethnicity'].str.contains('french')]['Description']

这会返回任何特定的字符串,但我想在不搜索每个特定种族值的情况下进行迭代.我也尝试将列转换为列表并迭代但似乎无法找到返回行的方法,因为它不再是DataFrame().

先感谢您!

解决方法:

您可以在种族转换为tolist的列中使用str.contains的值,然后按|连接什么是regex或:

print ('|'.join(df.Ethnicity.tolist()))
french|Italian|Danish|Dutch|English|Irish

mask = df.Description.str.contains('|'.join(df.Ethnicity.tolist()))
print (mask)
0     True
1    False
2    False
3     True
4     True
5     True
Name: Description, dtype: bool

#boolean-indexing
print (df[mask])
  Ethnicity          Description
0    french  Irish Dance Company
3     Dutch               french
4   English        Englishfrench
5     Irish       Irish-American

看起来你可以省略tolist():

print (df[df.Description.str.contains('|'.join(df.Ethnicity))])
  Ethnicity          Description
0    french  Irish Dance Company
3     Dutch               french
4   English        Englishfrench
5     Irish       Irish-American

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐