1# setting up a dummy dataframe
2raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'],
3 'age': [20, 19, 22, 21],
4 'favorite_color': ['blue', 'red', 'yellow', "green"],
5 'grade': [88, 92, 95, 70]}
6df = pd.DataFrame(raw_data, index = ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'])
7df
8
9#now 'age' will appear at the end of our df
10df = df[['favorite_color','grade','name','age']]
11df.head()
1In [7]: cols = df.columns.tolist()
2In [8]: cols
3Out[8]: [0L, 1L, 2L, 3L, 4L, 'mean']
4
5In [12]: cols = cols[-1:] + cols[:-1]
6
7In [13]: cols
8Out[13]: ['mean', 0L, 1L, 2L, 3L, 4L]
9
10In [14]: df = df[cols]
1#old df columns
2df.columns
3Index(['A', 'B', 'C', 'D'],dtype='***')
4#new column format that we want to rearange
5new_col = ['D','C','B','A'] #list of column name in order that we want
6
7df = df[new_col]
8df.columns
9Index(['D', 'C', 'B', 'A'],dtype='***')
10#new column order
1# Get column list in ['item1','item2','item3'] format
2df.columns
3# [0]output:
4Index(['item1','item2','item3'], dtype='object')
5
6# Copy just the list portion of the output and rearrange the columns
7cols = ['item3','item1','item2']
8
9# Resave dataframe using new column order
10df = df[cols]
11
1cols = df.columns.tolist()
2# Rearrange the list any way you want
3cols = cols[-1:] + cols[:-1]
4df = df[cols]
1You could also do something like this:
2
3df = df[['mean', '0', '1', '2', '3']]
4You can get the list of columns with:
5
6cols = list(df.columns.values)
7The output will produce:
8
9['0', '1', '2', '3', 'mean']