0

I have a data frame with different columns.One column x has value "a" and other column y has value "b", can I replace both values simultaneously using replace?

I can do it by two statments like

df["x"]=df["x"].replace("a","not a")
df["y"]=df["y"].replace("b","not b")

It works fine but can I do it in one statement like -

df["x","y"]=df["x","y"].replace(["a","b"],["not a","not b"]) ?
2
  • You can replace a string with a string, with another string by chaining another replace to the end.. Not sure how would you describe your suggestion.. Commented Jul 30, 2018 at 18:59
  • Are they changing to the same value? Why does it need to be on one line? I think this will run the risk of losing readability. Commented Jul 30, 2018 at 19:13

1 Answer 1

1

To index by multiple columns, create a list inside of the indexing operator. Note that the replace method on a DataFrame will replace every occurrence in all the columns (so it may behave differently if you have 'a' values in both columns but only wanted to replace in one of them).

df[['x', 'y']] = df[['x', 'y']].replace({'a':'not a','b':'not b'})
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much:)
I did with list instead of passing dictionary, even that is working. What is the difference if we pass dictionary or list as input in replace?

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.