Brian Brian - 2 months ago 14
Python Question

pandas series drop when multiindex is not unique

consider the

pd.Series
s


midx = pd.MultiIndex.from_product([list('ABC'), np.arange(3)])
s = pd.Series(1, midx)
s

A 0 1
1 1
2 1
B 0 1
1 1
2 1
C 0 1
1 1
2 1
dtype: int64


It is very convenient to use
drop
to get rid of cross sections. For example

s.drop('A')

B 0 1
1 1
2 1
C 0 1
1 1
2 1
dtype: int64


But if I make the index non-unique

s = s.append(pd.Series(0, pd.MultiIndex.from_tuples([('A', 2)]))).sort_index()
s

A 0 1
1 1
2 1
2 0
B 0 1
1 1
2 1
C 0 1
1 1
2 1
dtype: int64


Then the same
drop
no longer works.

s.drop('A')

A 0 1
1 1
2 1
2 0
B 0 1
1 1
2 1
C 0 1
1 1
2 1
dtype: int64


How do I drop like before

The desired result should be (this doesn't work, what does)

s.drop('B')

A 0 1
1 1
2 1
2 0
C 0 1
1 1
2 1
dtype: int64

Answer

I'm not sure why the s.drop('B') doesn't work but using the level=0 parameter does.

s.drop('B', level=0)

A  0    1
   1    1
   2    1
   2    0
C  0    1
   1    1
   2    1
dtype: int64
Comments