I would like to add a column to a dataframe between two columns in number labeled columns dataframe. In the following dataframe the first column corresponds to the index while the first row to the name of the columns.
df
0 0 1 2 3 4 5
1 6 7 4 5 2 1
2 0 3 1 3 3 4
3 9 8 4 3 6 2
I have tmp=[2,3,5]
that I want to put between the columns 4
and 5
, so
df
0 0 1 2 3 4 5 6
1 6 7 4 5 2 2 1
2 0 3 1 3 3 3 4
3 9 8 4 3 6 5 2
In pandas you can add/append a new column to the existing DataFrame using DataFrame. insert() method, this method updates the existing DataFrame with a new column. DataFrame. assign() is also used to insert a new column however, this method returns a new Dataframe after adding a new column.
After extraction, the column needs to be simply added to the second dataframe using join() function. This function needs to be called with reference to the dataframe in which the column has to be added and the variable name which stores the extracted column name has to be passed to it as the argument.
You can use insert
:
df.insert(4, 'new_col_name', tmp)
Note: The insert
method mutates the original DataFrame and does not return a copy.
If you use df = df.insert(4, 'new_col_name', tmp)
, df
will be None
.
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