Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pandas df.assign() with variable names?

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.

like image 859
eiram_mahera Avatar asked Sep 16 '19 05:09

eiram_mahera


People also ask

How do I assign a variable to a pandas DataFrame?

The syntax for the assign method is fairly simple. You type the name of your dataframe, then a “dot”, and then type assign() . Remember, the assign method is a Python method that's associated with dataframe objects, so we can use so-called “dot syntax” to call the method.

How do you assign values in DF?

if we want to modify the value of the cell [0,"A"] u can use one of those solution : df. iat[0,0] = 2. df.at[0,'A'] = 2.

How do you assign DataFrame column names?

To set column names of DataFrame in Pandas, use pandas. DataFrame. columns attribute. Assign required column names as a list to this attribute.


1 Answers

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
like image 182
Chris Avatar answered Oct 01 '22 07:10

Chris