部分匹配如果声明熊猫

时间:2017-02-15 18:54:49

标签: python pandas if-statement

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

如果列标题为'有“狗”这个词。在其中,然后在我的新专栏“Match'”中添加一行。

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

2 个答案:

答案 0 :(得分:3)

使用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

答案 1 :(得分:3)

只需使用pandas.Series.str.contains.

即可
>>> 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标志。

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

由于这是使用re.search,您可以使用常规正则表达方式检查多个字符串,例如

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