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

I would like to add a column to the data frame between two columns in the number of marked columns of the dataframe. In the following framework, the first column corresponds to the index, and the first row corresponds to the column name.

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]one that I want to put between columns 4and 5therefore

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 
+4
source share
2 answers

You can also use insert:

df.insert(4, "new_col_name", tmp)

Then change the column names, e.g. @Alexander .

Note. df.insert () has no inplace parameter

So, let's do the inplace operation and go back to None

. df = df.insert(4, "new_col_name", tmp)

+4

.

df2 = pd.concat([df, pd.DataFrame(tmp)], axis=1)

.

df2.columns = [0, 1, 2, 3, 4, 6, 5]

.

df2.sort_index(axis=1, inplace=True)

>>> df2
   0  1  2  3  4  5  6
0  6  7  4  5  2  2  1
1  0  3  1  3  3  3  4
2  9  8  4  3  6  5  2
+1

All Articles