Skip to content
Advertisement

How to reorder pandas dataframe based off list containing column order

Say I have a dataframe ‘df’ that contains a list of files and their contents:

JavaScript

How can I reorder this df if I have ordered lists of how the ‘Field’ column should be ordered?

JavaScript

So that the resulting df is re ordered like so (I am not trying to just sort ‘Field’ in reverse alphabetical order, this example is just coincidence):

JavaScript

Advertisement

Answer

First, put your new orders in a dictionary:

JavaScript

Then, create a new column with those values properly positioned according to the File values, and make Field the index and index it with the new column:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement