Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a level from a pandas MultiIndex

Tags:

python

pandas

I would like to completely remove a level from a MultiIndex

import pandas as pd
tuples = [(0, 100, 1000),(0, 100, 1001),(0, 100, 1002), (1, 101, 1001)]
index_3levels=pd.MultiIndex.from_tuples(tuples,names=["l1","l2","l3"])
print index_3levels.levels
[Int64Index([0, 1], dtype=int64), Int64Index([100, 101], dtype=int64), Int64Index([1000, 1001, 1002], dtype=int64)]

I would like to extract the first 2 levels, to achieve:

print index_2levels
MultiIndex
[(0, 100), (1, 101)]

droplevel drops the level but keeps the duplicates:

print index_3levels.droplevel("l3")
MultiIndex
[(0, 100), (0, 100), (0, 100), (1, 101)]

I could in principle call unique to remove them. However it does not look the right approach. Is there a more direct method?

like image 819
Andrea Zonca Avatar asked Jul 04 '13 13:07

Andrea Zonca


1 Answers

This could be an enhancement to droplevel, maybe by passing uniquify=True

In [77]: MultiIndex.from_tuples(index_3levels.droplevel('l3').unique())
Out[77]: 
MultiIndex
[(0, 100), (1, 101)]

Here's another way to do this

First create some data

In [226]: def f(i):
            return [(i,100,1000),(i,100,1001),(i,100,1002),(i+1,101,1001)]

In [227]: l = []

In [228]: for i in range(1000000):
             l.extend(f(i))

In [229]: index_3levels=pd.MultiIndex.from_tuples(l,names=["l1","l2","l3"])

In [230]: len(index_3levels)
Out[230]: 4000000

The method shown above

In [238]: %timeit MultiIndex.from_tuples(index_3levels.droplevel(level='l3').unique())
1 loops, best of 3: 2.26 s per loop

Let's split the index apart to 2 components, l1, and l2 and uniquify, much faster to unique these as these are Int64Index

In [249]: l2 = index_3levels.droplevel(level='l3').droplevel(level='l1').unique()

In [250]: %timeit index_3levels.droplevel(level='l3').droplevel(level='l1').unique()
10 loops, best of 3: 35.3 ms per loop

In [251]: l1 = index_3levels.droplevel(level='l3').droplevel(level='l2').unique()

In [252]: %timeit index_3levels.droplevel(level='l3').droplevel(level='l2').unique()
10 loops, best of 3: 52.2 ms per loop

In [253]: len(l1)
Out[253]: 1000001

In [254]: len(l2)
Out[254]: 2

Reassemble

In [255]: %timeit MultiIndex.from_arrays([ np.repeat(l1,len(l2)), np.repeat(l2,len(l1)) ])
10 loops, best of 3: 183 ms per loop

Total time about 270ms, pretty good speedup. Note that I think the ordering may be different, but I think some combination of np.repeate/np.tile will work

like image 130
Jeff Avatar answered Sep 24 '22 04:09

Jeff