Say I have a dataframe ‘df’ that contains a list of files and their contents:
JavaScript
x
6
1
File Field Folder
2
Users.csv Age UserFolder
3
Users.csv Name UserFolder
4
Cars.csv Color CarFolder
5
Cars.csv Model CarFolder
6
How can I reorder this df if I have ordered lists of how the ‘Field’ column should be ordered?
JavaScript
1
3
1
users_col_order = ['Name', 'Age']
2
cars_col_order = ['Model', 'Color']
3
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
1
6
1
File Field Folder
2
Users.csv Name UserFolder
3
Users.csv Age UserFolder
4
Cars.csv Model CarFolder
5
Cars.csv Color CarFolder
6
Advertisement
Answer
First, put your new orders in a dictionary:
JavaScript
1
5
1
mapping = {
2
'Users': ['Name', 'Age'],
3
'Cars': ['Model', 'Color'],
4
}
5
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
1
7
1
original_cols = df.columns
2
3
for k, v in mapping.items():
4
df.loc[df['File'] == k + '.csv', 'tmp'] = v
5
6
df = df.set_index('Field').loc[df['tmp']].reset_index().drop('tmp', axis=1)[original_cols]
7
Output:
JavaScript
1
7
1
>>> df
2
File Field Folder
3
0 Users.csv Name UserFolder
4
1 Users.csv Age UserFolder
5
2 Cars.csv Model CarFolder
6
3 Cars.csv Color CarFolder
7