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
?
答案 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