When creating a Pandas dataframe with a MultiIndex, the levels seem to always be sorted:
>>> pd.DataFrame([range(4)], columns=pd.MultiIndex.from_product([["b", "a"], [20, 10]]))
b a
20 10 20 10
0 0 1 2 3
>>> _.columns
MultiIndex(levels=[[u'a', u'b'], [10, 20]],
labels=[[1, 1, 0, 0], [1, 0, 1, 0]])
(Note how levels is sorted.) Is this guaranteed? Knowing this can help write robust code (since we can then rely on a simple property of MultiIndices).
I can't find any guarantee in the documentation (but then this doesn't mean that it couldn't be there!).
There are also old examples (from 2015) that show a different behavior, but maybe does Pandas now offer guarantees on the ordering of levels (in the same way as Python 3.6 offers a guarantee on the order of keys in dictionaries)?