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.
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.
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.
To set column names of DataFrame in Pandas, use pandas. DataFrame. columns attribute. Assign required column names as a list to this attribute.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With