Pairwise rename columns for variable even number of dataframe columns

Question:

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.

Asked By: Luka Banfi

||

Answers:

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)
Answered By: mozway
df1.T.assign(col2=lambda dd:['Item {} ID',' Item {} Title']*(len(dd)//2))
    .assign(col2=lambda dd:dd.apply(lambda ss:ss.col2.format(int(ss.name)//2+1),axis=1))
    .set_index('col2').T

col2  Item 1 ID   Item 1 Title  Item 2 ID   Item 2 Title
0             1              3          5              7
1             2              4          6              8
Answered By: G.G
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.