简体   繁体   中英

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 dataframe is expected to have a variable # of columns (this is part of a larger script). i want to arrange the columns in a way that the last 2 columns will be the second and third consecutively, then all the remaining columns will follow (while the first column stays as first column). If result1 is known to have 6 columns, then i could use:

result2=result1.iloc[:,[0,4,5,1,2,3]] #this works fine. 

BUT, i need the 1,2,3 to be in a range format as it is not practical to enter the whole of the numbers for each df. So, i thought of using:

result2=result1.iloc[:,[0,len(result1.columns), len(result1.columns)-1, 1:len(result1.columns-2]]
#Assuming  6 columns :  0,           5        , 4                     ,  1,  2, 3

That would be the idea way but this is creating syntax errors. Any suggestions to fix this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM