19

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.

2
  • 1
    Why not just df[new_column] = other_df['Column1'].values? Commented Sep 16, 2019 at 5:42
  • 5
    @Chris assign is useful in a longer chain of multiple operations Commented Sep 16, 2019 at 5:43

1 Answer 1

22

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. Does this have any performance repercussions against df[new_column] = other_df['Column1'].values1 ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.