0

I can't figure out how to write this If df['col1']=='A' then df['col2'].replace('X','Y', inplace = True)

I write something like df[df['col1'] == 'A']['col2'].replace('X','Y', inplace = True) but it is giving me an error and I can't work out a solution to it.

I am trying to get a value in a column replaced, if a condition is met in another column

  • Does this answer your question? [Conditional Replace Pandas](https://stackoverflow.com/questions/21608228/conditional-replace-pandas) Specifically, look at the answer given by @seeiespi: https://stackoverflow.com/a/48795837/12131013 – jared Jun 07 '23 at 23:52

1 Answers1

1

The problem is inplace=True. You are trying that way to modify the "source" dataframe, but that dataframe is just a partial view (a slice) of another dataframe, so it is "read-only".

It is a little bit like
df[(df.col1=='A') & (df.col2=='X')]['col2'] = 'Y'

That would fail for the same reason: can't modify ['col2'] of dataframe df[(df.col1=='A') & (df.col2=='X')], since that dataframe is a slice of df.

What you can do is

df.loc[(df.col1=='A') & (df.col2=='X'), 'col2'] = 'Y'
chrslg
  • 9,023
  • 5
  • 17
  • 31