Home > front end >  Replace transformation: What is the right way to do it?
Replace transformation: What is the right way to do it?

Time:07-25

I do this to replace a character in a string:

df['msg'] = df['msg'].str.replace(u'X','W')

And get this warning:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

Then, I try to do this same transformation the right way (I thought) to avoid that warning:

df.loc[:,'msg'] = df.loc[:,'msg'].str.replace(u'X','W')

But, I am still getting the same warning, even though both codes works fine.

What is the correct way to do this kind of transformation?

CodePudding user response:

This warning can be resolved by using the method copy():

df.loc[:,'msg'] = df['msg'].str.replace(u'X','W').copy()

Or assign()

df = df.assign(msg=df['msg'].str.replace(u'X','W'))
  • Related