0

I have a Dataframe df:

name     rank
A    captain, general, soldier
B    general, foo, major
C    foo
D    captain, major
E    foo, foo, foo

I want to check if any cell in the column rank consists of foo and if it does replace the whole cell with foo.

Expected output:

name     rank
A    captain, general, soldier
B    foo
C    foo
D    captain, major
E    foo

How can I do this?

2

4 Answers 4

1
df['rank'].replace('.*foo.*', 'foo', regex=True, inplace=True)
# OR
df['rank'].mask(df['rank'].str.contains('foo'), 'foo', inplace=True)
# OR
df.loc[df['rank'].str.contains('foo'), 'rank'] = 'foo'

Output:

  name                       rank
0    A  captain, general, soldier
1    B                        foo
2    C                        foo
3    D             captain, major
4    E                        foo
Sign up to request clarification or add additional context in comments.

Comments

1

You can apply a lambda function to the column :

df["rank"] = df["rank"].apply(lambda x: "foo" if "foo" in x.split(", ") else x)

Splitting on the separator allows to check for words. For example, the world "foobar" wouldn't trigger the transformation on its row.

Edit: Thanks to BeRT2me for suggesting to split by ', '.

Comments

0
mask = df['rank'].str.contains('foo')
df.loc[mask, 'rank'] = 'foo'

Comments

-1
if df['rank'].str.contains('foo').any():
 df['rank']='foo'

1 Comment

wouldn't that just replace the whole series with foo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.