omdurg
omdurg

Reputation: 330

Is there a way to start pandas add_prefix column index from 1

I have gone through pandas.Dataframe.add_prefix. I have a set of columns being dynamically created, so am using pd.df.add_prefix for those columns.

For example, newly created columns are:

column0         column1          column2

It's starting from 0. Is there a way to start column naming from 1, like:

column1         column2          column3

Edit:

Dataframe:

df = pd.DataFrame([[34007, [3330193, 349723]], [126063, [349723,7901731]]], 
columns=['prod_1', 'prod_2'])

Code:

pd.DataFrame(df['prod_2'].values.tolist()).add_prefix('column').join(df['prod_1'])

Output that I got:

column0       column1        prod_1
3330193       349723         34007
349723        7901731        126063

Expected output:

column1       column2        prod_1
3330193       349723         34007
349723        7901731        126063

Please note only names of generated columns change in expected output, values remain same

Thanks for the help!!

Upvotes: 3

Views: 629

Answers (1)

anky
anky

Reputation: 75120

You can use df.rename to rename the columns with f strings:

out = (pd.DataFrame(df['prod_2'].values.tolist())
       .rename(columns=lambda x: f"column{int(x)+1}").join(df['prod_1']))

   column1  column2  prod_1
0  3330193   349723   34007
1   349723  7901731  126063

Upvotes: 4

Related Questions