0

Please Note: I am trying to only trying to replace the values of a specific column, NOT the entire dataframe. I have not been able to find any SO questions that refer to using .replace() on a single column within a dataframe.

I'm trying to isolate a single column within a Pandas dataframe and replace a specific substring whenever it appears in the column. I've attempted to use .iloc and .replace(), but for some reason that seems to work when I save the copy down as a new dataframe. Is there no way to utilize .replace on a single column (or two) within a dataframe? As of now, I've had to resort to replacing the substring in the entire data frame, then manually changing some of the values back (this is terrible practice and inherently against the principles of Python) any and all help would be greatly appreciated. Examples of my code are below:

The following is what I originally attempted; however, it only works if I save the selection into a new data frame (I need the original dataframe in it's entirety after the changes are made)

Values replaced successfully:

df_1 = df.iloc[:, [13, 20]].replace({' AD': ' AB'}, regex=True)

Values not replaced successfully:

df.iloc[:, [13, 20]].replace({' AD': ' AB'}, regex=True)

What I've resorted to:

df = df.replace({' AD': ' AB'}, regex=True)    
df = df.replace({'BAB': 'BAD'}, regex=True)
df = df.replace({'BAB': 'BAD'}, regex=True)
df = df.replace({'ABVERTISE': 'ADVERTISE'}, regex=True)

Please let me know if any other details are needed - I feel like there is a super simple solution.. I just can't seem to find it anywhere

ls101
  • 177
  • 5
  • 17
  • 1
    The operation isn't inplace... right? Don't assume it is. `df.iloc[:, [13, 20]] = df.iloc[:, [13, 20]].replace({' AD': ' AB'}, regex=True)` is what you should've done. – cs95 Jan 17 '18 at 00:30
  • Thanks ColdSpeed, this worked for me – ls101 Jan 17 '18 at 00:37

0 Answers0