Reputation: 380
I'm merging two data frames which works fine but the new column is placed on the end. I would like it to be the 3rd column or index 2. So far I have this which works but I'm wondering if there is a better way.
overlap = overlap.merge(df_comp, how='left')
cols = overlap.columns.tolist()
cols.insert(2, cols.pop(cols.index('cr')))
overlap = overlap.reindex(columns= cols)
To further explain the names and number of columns if the final dataframe will change from day to day so the solution will need to be dynamic. Is there a clean one or two line way of doing this?
Upvotes: 0
Views: 700
Reputation: 1420
One quick hack is to set the first 2 columns and the last added columns as index, then reset the index, which will place them as the first 3 columns:
import numpy as np
overlap.set_index(overlap.columns[np.r_[0:2,-1]].to_list()).reset_index()
np.r_[0:2, -1]
essentially take the column names for column 0, 1 and -1 (the last column appended).
Upvotes: 1