Rearranging A Non-consecutive Order Of Columns In Pandas Dataframe
I have a pandas data frame (result) df with n (variable) columns that I generated using the merge of two other data frames: result1 = df1.merge(df2, on='ID', how='left') result1 d
Solution 1:
Instead of using slicing syntax, I'd just build a list and use that:
>>> df
0 1 2 3 4 5
0 0 1 2 3 4 5
1 0 1 2 3 4 5
2 0 1 2 3 4 5
3 0 1 2 3 4 5
4 0 1 2 3 4 5
>>> ncol = len(df.columns)
>>> df.iloc[:,[0, ncol-1, ncol-2] + list(range(1,ncol-2))]
0 5 4 1 2 3
0 0 5 4 1 2 3
1 0 5 4 1 2 3
2 0 5 4 1 2 3
3 0 5 4 1 2 3
4 0 5 4 1 2 3
Post a Comment for "Rearranging A Non-consecutive Order Of Columns In Pandas Dataframe"