Skip to content

Instantly share code, notes, and snippets.

@nowox
Created April 1, 2017 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nowox/dd07f4cebb31a84ac98adb905b0379b8 to your computer and use it in GitHub Desktop.
Save nowox/dd07f4cebb31a84ac98adb905b0379b8 to your computer and use it in GitHub Desktop.
Sort index in pandas
In [297]: d = {0: {'foo': {'a': 12.68, 'b': 54.44, 'c': 83.98},
...: 'bar': {'a': 11.73, 'b': 53.34, 'c': 82.93}},
...: 2: {'foo': {'a': 11.12, 'b': 57.99, 'c': 81.05},
...: 'bar': {'a': 10.05, 'b': 56.12, 'c': 80.01}},
...: 1: {'foo': {'a': 13.41, 'b': 54.32, 'c': 82.74},
...: 'bar': {'a': 12.77, 'b': 53.15, 'c': 82.01}}}
In [298]: ds = (pd.DataFrame.from_dict(d, orient='index')
...: .stack().apply(pd.Series)
...: .rename_axis(['experiment', 'setup']))
In [299]: ds.sort_index(level = 0, inplace = True)
In [300]: ds
Out[300]:
a b c
experiment setup
0 foo 12.68 54.44 83.98
bar 11.73 53.34 82.93
1 foo 13.41 54.32 82.74
bar 12.77 53.15 82.01
2 foo 11.12 57.99 81.05
bar 10.05 56.12 80.01
@abast
Copy link

abast commented Apr 1, 2017

Now I start to see the weiredness ... it looks like 'foo' and 'bar' is sorted like 'foo' < 'bar'. Why should that be the case? I tried to set ascending = False, here it becomes even more obvious ...

@abast
Copy link

abast commented Apr 1, 2017

Sorting 'foo' and 'bar' seems to be a special case. Try 'f' instead of 'foo' and 'b' instead of 'bar'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment