Reputation: 330
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
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