Sort pandas data based on list

I would like to sort the following data framework:

Region LSE North South 0 Cn 33.330367 9.178917 1 Develd -36.157025 -27.669988 2 Wetnds -38.480206 -46.089908 3 Oands -47.986764 -32.324991 4 Otherg 323.209834 28.486310 5 Soys 34.936147 4.072872 6 Wht 0.983977 -14.972555 

I would like to sort it so that the LSE column is reordered based on the list:

 lst = ['Oands','Wetnds','Develd','Cn','Soys','Otherg','Wht'] 

Of course, other columns must also be reordered accordingly. Is there any way to do this in pandas?

+8
python pandas
source share
1 answer

The improved Categorical support in pandas version 0.15 allows you to do this easily:

 df['LSE_cat'] = pd.Categorical( df['LSE'], categories=['Oands','Wetnds','Develd','Cn','Soys','Otherg','Wht'], ordered=True ) df.sort('LSE_cat') Out[5]: Region LSE North South LSE_cat 3 3 Oands -47.986764 -32.324991 Oands 2 2 Wetnds -38.480206 -46.089908 Wetnds 1 1 Develd -36.157025 -27.669988 Develd 0 0 Cn 33.330367 9.178917 Cn 5 5 Soys 34.936147 4.072872 Soys 4 4 Otherg 323.209834 28.486310 Otherg 6 6 Wht 0.983977 -14.972555 Wht 

If this is only a temporary order, then keeping the LSE column as a Categorical may not be what you want, but if this ordering is what you want to be able to use several times in different contexts, Categoricals is a great solution.

+11
source share

All Articles