sonu
sonu

Reputation: 29

How the rename all columns using regular expression in Python?

I have columns in pandas data frame that look like:

Variable Names    
name1 [a]

name2 [b]

name3 [c]

I am using the following code to remove all the square brackets and everything within those brackets from all the variable names. This is the code I am using:

import re 
df = df.rename(columns=lambda n: n.replace(r'[\d+.*', r''))

This code is not working. How can I modify this code to get it to work?

Thanks!

Upvotes: 0

Views: 1452

Answers (1)

ak_slick
ak_slick

Reputation: 1016

This should do what you are looking for.

df.rename(columns=lambda x: re.sub("[\[].*?[\]]", "", x))

Upvotes: 1

Related Questions