Skip to content Skip to sidebar Skip to footer

Key Error And Multiindex Lexsort Depth

I have a set of tab delimited files that I have to go through read them, use them as pandas dataframe, do a whole bunch of operations on them and then merge them back to one excel

Solution 1:

Docs are quite good. If you work with multi-indexes it pays to read them thru (several times!), see here

In [9]: df = DataFrame(np.arange(9).reshape(-1,1),columns=['value'],index=pd.MultiIndex.from_product([[1,2,3],['a','b','c']],names=['one','two']))

In [10]: df
Out[10]: 
         value
one two       
1   a        0
    b        1
    c        22   a        3
    b        4
    c        53   a        6
    b        7
    c        8

In [11]: df.index.lexsort_depth
Out[11]: 2

In [12]: df.sortlevel(level=1)
Out[12]: 
         value
one two       
1   a        02   a        33   a        61   b        12   b        43   b        71   c        22   c        53   c        8

In [13]: df.sortlevel(level=1).index.lexsort_depth
Out[13]: 0

In [9]: df = DataFrame(np.arange(9).reshape(-1,1),columns=['value'],index=pd.MultiIndex.from_product([[1,2,3],['a','b','c']],names=['one','two']))

In [10]: df
Out[10]: 
         value
one two       
1   a        0
    b        1
    c        22   a        3
    b        4
    c        53   a        6
    b        7
    c        8

In [11]: df.index.lexsort_depth
Out[11]: 2

In [12]: df.sortlevel(level=1)
Out[12]: 
         value
one two       
1   a        02   a        33   a        61   b        12   b        43   b        71   c        22   c        53   c        8

In [13]: df.sortlevel(level=1).index.lexsort_depth
Out[13]: 0

Update:

sortlevel will be deprecated so use sort_index i.e

df.sort_index(level=1)

Post a Comment for "Key Error And Multiindex Lexsort Depth"