0

I have a pandas dataframe like:

   _Ab  _Bc   C    D   _Ef  _Fg
0   a    4    7    1    5    a
1   b    5    8    3    3    a
2   c    4    9    5    6    a
3   d    5    4    7    9    b
4   e    5    2    1    2    b
5   f    4    3    0    4    b

I want to remove the starting _ present in some of the column names. Obviously I can replace them one at a time but that would be very inefficient as I have a lot of columns. So how can I do this efficiently?

1
  • What is number of columns? Commented Aug 8, 2019 at 13:11

2 Answers 2

2

Use list comprehension with if-else and startswith:

df.columns = [x.lstrip('_') if x.startswith('_') else x for x in df.columns]

Another solutions try left strip _ from all columns:

df.columns = [x.lstrip('_') for x in df.columns]

Or with Index.str.lstrip:

df.columns = df.columns.str.lstrip('_')

Or with rename:

df = df.rename(columns=lambda x: x.lstrip('_'))
print (df)
  Ab  Bc  C  D  Ef Fg
0  a   4  7  1   5  a
1  b   5  8  3   3  a
2  c   4  9  5   6  a
3  d   5  4  7   9  b
4  e   5  2  1   2  b
5  f   4  3  0   4  b
Sign up to request clarification or add additional context in comments.

5 Comments

Tried your code, but I am getting this error: AttributeError: 'Index' object has no attribute 'strip'
@Ank - Do you try df.columns = df.columns.lstrip('_') instead df.columns = df.columns.str.lstrip('_') - missing str?
Now I am getting AttributeError: 'Index' object has no attribute 'lstrip'
You're failing to type the StringMethods accessor. Instead of writing df.columns.lstrip(.) write df.columns.str.lstrip(.) (full stop in method invocation standing in for assorted parameters)
@Ank - how working first solution df.columns = [x.lstrip('_') if x.startswith('_') else x for x in df.columns] ?
0

This should work for you:

df.columns = [c.lstrip("_") for c in df.columns]

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.