16

I want to add a new column in a dataframe with values from some other dataframe. My new column name is a variable and I cannot hardcode it.

new_column = "my_new_column_name" 
df = df.assign(new_column=other_df['Column1'].values)

The problem is that, I am getting a new column named new_column. What I expect is a column named my_new_column_name

Can anyone please suggest a solution for this.

smci
  • 32,567
  • 20
  • 113
  • 146
eiram_mahera
  • 950
  • 9
  • 25

1 Answers1

18

You can make a dict and unpack:

Given df:

print(df)
   col1  col2
0     1    10
1     2    20
2     3    30

new_column = "my_new_column_name" 
df = df.assign(**{new_column: df['col1'].values})
print(df)

Output:

   col1  col2  my_new_column_name
0     1    10                   1
1     2    20                   2
2     3    30                   3
Chris
  • 29,127
  • 3
  • 28
  • 51
  • Thanks for the answer. Does this have any performance repercussions against `df[new_column] = other_df['Column1'].values1` ? – Rishabh Bhatt Nov 16 '22 at 19:15