1

Below is a dataframe and the goal is to strip the column as well as the dataframe values.

df = pd.DataFrame({'A ': ['1   ', '   2  '], '  B': ['4 ', '5 '], 'C': ['8 ','9']})

|A | B|C|

|1 |4 |8 |

| 2 |5 |9|

def strip(data):
    data.columns = data.columns.str.strip()
    data = data.applymap(str.strip)

But it's not working (return the spaced dataframe) when execute the function as below, but when remove the def() it can work

strip(df)

How to use the def() in order to strip the data? Looking forward to your solutions. Thank you so much!

K.W. LEE
  • 63
  • 5

1 Answers1

1

You need to return the dataframe, and assign it back. Because the operation you are doing is immutable, a new copy of the dataframe is created within the scope of function strip, and the outer object has no effect.

def strip(data):
    data.columns = data.columns.str.strip()
    data = data.applymap(str.strip)
    return data

df = strip(df)
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45