Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to add a column to a pandas dataframe between two columns?

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 
like image 492
emax Avatar asked Apr 05 '16 22:04

emax


People also ask

How do I create a new column in pandas from existing columns?

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.

How do you add a column to a DataFrame to another data frame?

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.


1 Answers

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.

like image 196
ayhan Avatar answered Sep 29 '22 17:09

ayhan