Cannot figure out how to drop a list of multi-level rows from a pandas dataframe with greater than 3 levels, without resorting to a for loop.
This works fine when explicitly defining all values in the index as answered by: Pandas Multiindex dataframe remove rows
e.g.
mask = dfmi.index.isin(( ('A0','B0', 'C0'), ('A2','B3', 'C4') ))
dfmi.loc[~mask,:]
However when one wants to accept all possible third level:
dfmi.index.isin(( ('A0','B0', slice(None)), ('A2','B3', slice(None)) ))
The result TypeError: unhashable type: 'slice'
Currently I am achieving this with the following code:
import numpy as np
import pandas as pd
def mklbl(prefix, n):
return ["%s%s" % (prefix, i) for i in range(n)]
miindex = pd.MultiIndex.from_product([mklbl('A', 4),
mklbl('B', 4),
mklbl('C', 10)])
dfmi = pd.DataFrame(np.arange(len(miindex) * 2)
.reshape((len(miindex), 2)),
index=miindex).sort_index().sort_index(axis=1)
As = ['A0', 'A2']
Bs = ['B1', 'B3']
for a,b in zip(As, Bs):
dfmi_drop_idx = dfmi.loc[(a, b, slice(None)), :].index
dfmi.drop(dfmi_drop_idx, inplace=True, errors='ignore')
(A0, B1, :)and(A2, B3, :)? Because that's a bit unclear from your question.