how to change the order of columns in pandas code example
Example 1: python change column order in dataframe
cols = df.columns.tolist()
cols = cols[-1:] + cols[:-1]
df = df.reindex(cols, axis=1)
Example 2: how to change the column order in pandas dataframe
df = df.reindex(columns=column_names)
Example 3: dataframe, sort by columns
final_df = df.sort_values(by=['2'], ascending=False)
Example 4: pandas reorder columns
df.columns
Index(['item1','item2','item3'], dtype='object')
cols = ['item3','item1','item2']
df = df[cols]
Example 5: python pandas change column order
In [39]: df
Out[39]:
0 1 2 3 4 mean
0 0.172742 0.915661 0.043387 0.712833 0.190717 1
1 0.128186 0.424771 0.590779 0.771080 0.617472 1
2 0.125709 0.085894 0.989798 0.829491 0.155563 1
3 0.742578 0.104061 0.299708 0.616751 0.951802 1
4 0.721118 0.528156 0.421360 0.105886 0.322311 1
5 0.900878 0.082047 0.224656 0.195162 0.736652 1
6 0.897832 0.558108 0.318016 0.586563 0.507564 1
7 0.027178 0.375183 0.930248 0.921786 0.337060 1
8 0.763028 0.182905 0.931756 0.110675 0.423398 1
9 0.848996 0.310562 0.140873 0.304561 0.417808 1
In [40]: df = df[['mean', 4,3,2,1]]