Home > front end >  Pandas pairwise rename columns for variable even number of dataframe columns
Pandas pairwise rename columns for variable even number of dataframe columns

Time:05-13

Example dataframe:

   0  1
0  1  3
1  2  4

Additional example dataframe:

   0  1  2  3
0  1  3  5  7
1  2  4  6  8

Expected result after pairwise renaming columns of above dataframes:

   Item 1 ID  Item 1 Title
0          1             3
1          2             4

   Item 1 ID  Item 1 Title  Item 2 ID  Item 2 Title
0          1             3          5             7
1          2             4          6             8

Renaming every dataframe column identically apart from incrementing iterator:

df.rename(columns={i: f'Item {i 1} ID' for i in df.columns})

Static dictionary mapping can't be used due to variable even number of dataframe columns.

CodePudding user response:

IIUC, you can use a simple list comprehension:

df.columns = [f'Item {i 1} {x}' for i in range(len(df.columns)//2)
                                for x in ['ID', 'Title']]

output:

   Item 1 ID  Item 1 Title  Item 2 ID  Item 2 Title
0          1             3          5             7
1          2             4          6             8

If you need to rename in a pipeline, use:

def renamer(df):
    return df.set_axis([f'Item {i 1} {x}' for i in range(len(df.columns)//2)
                                          for x in ['ID', 'Title']],
                       axis=1)

df.pipe(renamer)
  • Related