Home > Blockchain >  How to rename dataframe columns in a for in loop function
How to rename dataframe columns in a for in loop function

Time:06-16

I'm kind of new to Python. I have a pandas dataframe which has about 400 columns. All columns have this structure:

p900_70
p901_70
p902_70
p903_70
...

I need to rename all these variables, so that they look like this:

p900_
p901_
p902_
p903_

As there are so many variables, I need to use a for in loop function to achieve this objective. I think it could be something like this but with a rename part inside of the loop

def equalize70(x):
  for i in x.columns.values:
    result = i[:-2]
    yield result

Any suggestions? Thanks in advance

CodePudding user response:

You can use rstrip

df.columns = df.columns.str.rstrip('70')
  • Related