34

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 this is not working, anything I did wrong here?

2
  • If the empty space is at the end of the column names, shouldn't it be re.sub(' $', '')? Commented Oct 22, 2014 at 4:06
  • sorry for the wrong regex there, I tried the corrected one but python responded type error Commented Oct 22, 2014 at 4:07

3 Answers 3

55

I should have used rename with re.sub:

import re
raw_data = raw_data.rename(columns=lambda x: re.sub(' $','',x))

Or to change in-place:

raw_data.rename(columns=lambda x: re.sub(' $','',x), inplace=True)
Sign up to request clarification or add additional context in comments.

3 Comments

This will only remove 1 space.Use this if you want to remove all.raw_data.columns.values = re.sub(r'[ ]*$','',raw_data.columns.values)
would this work if the resulting column names were non-unique?
I tried my hand at looping through columns [for col in df.columns], using regex to identify what I needed to remove, and then re-name the columns one-by-one, which worked just fine, but was very slow. Your solution is much more performant! (for context: I was stripping a column-counter, i.e. (1), (2), ... (300), so that's why I needed regex)
10

I would recommend using pandas.Series.str.strip

df.columns = df.columns.str.strip()

Comments

5

The answer from @Christian is probably right for this specific question, but to the more general question about replacing names in the columns, I would suggest to create a dictionary comprehension and pass it to the rename function:

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

In my case, I wanted to add something to the beginning of each column, so:

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

You can use the inplace=True parameter to actually make the change in the dataframe.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.