Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas pairwise rename columns for variable even number of dataframe columns

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading