Home > database >  Automatically Rename Columns in Pandas using string and number
Automatically Rename Columns in Pandas using string and number

Time:01-04

I have the current DataFrame:

df = pd.DataFrame([[-1, 2, 1, 3], [4, 6, 7,8], [-2, 10, 11, 13], [5, 6, 8, 9]], columns=['0', '1', '2', '3'])

I am trying to automatically rename every other column so that the first two are lo1, up1, lo2, up2. This is just an example, but I was hoping for a way to develop this for an entire DataFrame of many columns.

Thanks.

CodePudding user response:

An efficient approach is to use itertools.product:

from itertools import product

cols = [f'{a}{b 1}' for b,a in  product(range(len(df. columns)//2), ['lo','up'])]

df.columns = cols

Output:

   lo1  up1  lo2  up2
0   -1    2    1    3
1    4    6    7    8
2   -2   10   11   13
3    5    6    8    9

CodePudding user response:

You can use list comprehension to take every couple of column indices, rename them and put them back in:

df.columns = [x for i in range(1, len(df.columns)//2 1) for x in ['lo' str(i), 'up' str(i)]]

Output:

   lo1  up1  lo2  up2
0   -1    2    1    3
1    4    6    7    8
2   -2   10   11   13
3    5    6    8    9

CodePudding user response:

Here's one approach:

import pandas as pd

df = pd.DataFrame([[-1, 2, 1, 3], [4, 6, 7,8], [-2, 10, 11, 13], [5, 6, 8, 9]], columns=['0', '1', '2', '3'])

max_nr = int(len(df.columns)/2)

for i in range(max_nr):
    df.rename(columns={'{}'.format(i*2):'lo{}'.format(i), '{}'.format(i*2 1):'hi{}'.format(i)}, inplace=True)

output:

lo0 hi0 lo1 hi1
0 -1 2 1 3
1 4 6 7 8
2 -2 10 11 13
3 5 6 8 9
  •  Tags:  
  • Related