Python: how to add a column to a pandas dataframe between two columns?
First concatenate your column to your dataframe.
df2 = pd.concat([df, pd.DataFrame(tmp)], axis=1)
Then rename the columns to the desired end result.
df2.columns = [0, 1, 2, 3, 4, 6, 5]
Now sort on the renamed columns.
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
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
.