shifting specific column to before/after specific column in dataframe - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: shifting specific column to before/after specific column in dataframe (/thread-16885.html) |
shifting specific column to before/after specific column in dataframe - theinzawoo - Mar-19-2019 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 RE: shifting specific column to before/after specific column in dataframe - scidam - Mar-19-2019 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']]
RE: shifting specific column to before/after specific column in dataframe - theinzawoo - Mar-19-2019 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! RE: shifting specific column to before/after specific column in dataframe - theinzawoo - Mar-19-2019 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] RE: shifting specific column to before/after specific column in dataframe - scidam - Mar-19-2019 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 |