部分匹配If语句Pandas

2024-06-28 19:45:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在数据帧(标题)的某一列中找到部分字符串匹配。理想情况下,我希望pandas在部分字符串匹配为true时创建一个true false列,如果字符串匹配为false,则创建false列。我想要一个def函数来创建if/else语句,因为我的数据集非常大。在

如果列“Title”中包含单词“dog”,那么在我的新列“Match”中的该行中输入true。在

Old Dataframe example:

Title          Author Name  
Dogs R Us      John Smith
Pigs can Fly   Henry White
Dog Games      Adam James         


New Dataframe example:
Title          Author Name      Match  
Dogs R Us      John Smith       True
Pigs can Fly   Henry White      False
Dog Games      Adam James       True

Tags: 数据字符串namefalsetruedataframetitleexample
2条回答

使用str.contains

In [832]: df.Title.str.contains('Dog')
Out[832]:
0     True
1    False
2     True
Name: Title, dtype: bool

In [833]: df['Match'] = df.Title.str.contains('Dog')

In [834]: df
Out[834]:
          Title  Author Name  Match
0     Dogs R Us   John Smith   True
1  Pigs can Fly  Henry White  False
2     Dog Games   Adam James   True

只需使用^{}.

>>> df
          title
0     dogs r us
1  pigs can fly
2     dog games

>>> df['Match'] = df.title.str.contains('dog')

>>> df
          title  Match
0     dogs r us   True
1  pigs can fly  False
2     dog games   True

如果希望检查不区分大小写,可以使用re.IGNORECASE标志。在

^{pr2}$

因为这是使用re.search,所以可以用常规的regex方法检查多个字符串,比如

>>> df['Match'] = df.title.str.contains('dog|cats', flags=re.IGNORECASE)

相关问题 更多 >