Python Forum

Full Version: shifting specific column to before/after specific column in dataframe
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In dataframe,
a b f g c d e i j h
0 1 1 1 1 1 1 1 1 1 1
1 0 0 1 0 0 1 1 1 1 0
2 1 1 1 1 1 0 0 0 0 1
3 1 0 1 0 0 1 1 1 1 0
4 1 1 1 1 1 0 1 0 0 1
5 1 0 1 0 0 1 1 1 1 0
6 1 1 1 1 1 0 1 0 1 1
7 0 0 0 0 0 0 1 0 1 0
8 1 1 1 1 1 1 1 1 1 1
9 0 0 0 0 0 0 0 0 1 0
10 1 1 1 1 1 1 1 1 1 1


I want to shift these three : 'c','d','e' to the place of after b' and column 'h' to place after 'g'.

My idea is shifting the specific columns to place after/ before specific columns in dataframe for wider purpose . please suggest me! Thanks
You can specify the order of columns as you want, e.g.:

x=pd.DataFrame({'a': [1,2,3], 'b':[3,4,5], 'c':[5,6,7]})
x = x[['b','c','a']]
Output:
b c a 0 3 5 1 1 4 6 2 2 5 7 3
In my data set,
there are 699 columns , I want to move column number : 694,695 to 26 and 27 respectively.
How is your suggestion!
x=df.columns.get_loc('col') # getting column index , the place before that column

var_list=new_var # list of columns that are need to moved or order if multiple column and they are in
sequence position .
new_position = x
for var in var_list:
cols = df.columns.tolist()
column_to_move = var
new_position += 1
cols.insert(new_position, cols.pop(cols.index(column_to_move)))
df = df[cols]
Luckily, Python is programming language
and we don't need to type all items manually.

Your code would be something like this:

columns = ['col%s' % k for k in range(700)] # df.columns.tolist()
col694 = columns.pop(694)
col695 = columns.pop(694)
columns.insert(26, col694)
columns.insert(27, col695)
# df = df[columns] # reorder columns