Python str.contains function related to other columns

时间:2018-02-09 03:56:33

标签: python pandas

I have a table that includes title, genre columns, and I need to change genre columns if title columns have a word blue. But the thing is I have many blue names in title, so I want to change only a specific genre type. ex:

title     genre                       title      genre
blue      x                           blue        x
red       x          ------->         red         x
blue      y                           blue        ychanged
red       y                           red         y

I used this but this function changed all genre if title has blue

df['genre'][df.title.str.contains('blue')] = 'ychanged'

How can I make a specific str.contains?

2 个答案:

答案 0 :(得分:4)

您可以使用&

df.loc[df.title.str.contains('blue') & df.genre.isin(['y']), 'genre'] = 'ychanged'

答案 1 :(得分:2)

您可以使用以下逻辑表达式直接索引所需的行:

代码:

df.loc[df.title.str.contains('blue') & (df.genre == 'y'), 'genre'] = 'ychanged'

测试代码:

df = pd.read_fwf(StringIO(u"""
    title     genre  
    blue      x      
    red       x      
    blue      y      
    red       y      """), header=1)

print(df)

df.loc[df.title.str.contains('blue') & (df.genre == 'y'), 'genre'] = 'ychanged'

print(df)

结果:

  title genre
0  blue     x
1   red     x
2  blue     y
3   red     y

  title     genre
0  blue         x
1   red         x
2  blue  ychanged
3   red         y