Renaming a column in a dataframe for Pandas using regex

I have a dataframe made by Pandas that I want to remove the empty space at the end of each column name. I tried something like:

raw_data.columns.values = re.sub(' $','',raw_data.columns.values)

But it does not work, something I did wrong here?

+8
source share
3 answers

I had to use the package re:

raw_data = raw_data.rename(columns=lambda x: re.sub(' $','',x))
+12
source

I would recommend using

df.columns = df.columns.str.stripe()
0
source

@Christian, , , :

df.rename(columns={element: re.sub(r'$ (.+)',r'\1', element, flags = re.MULTILINE) for element in df.columns.tolist()})

- , :

df.rename(columns={element: re.sub(r'(.+)',r'x_\1', element) for element in df.columns.tolist()})

inplace = True, .

0

All Articles