You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have checked that this issue has not already been reported.
I have confirmed this bug exists on the latest version of pandas.
(optional) I have confirmed this bug exists on the master branch of pandas.
This is about trying to reindex a MultiIndex level to add keys to avoid a KeyError.
This code could be more minimalist and more generic but the context in which the error arose might be helpful..
When using groupby unnecessary keys are eliminated..
idx = pd.IndexSlice
df = pd.DataFrame([
['A', 'cat', 10],
['A', 'cat', 20],
['B', 'dog', 30],
['B', 'cat', 40]
], columns = ['Label', 'Animal', 'Score'])
g = df.groupby(['Label', 'Animal']).agg('sum')
g.index
>>> MultiIndex([('A', 'cat'),
('B', 'cat'),
('B', 'dog')],
names=['Label', 'Animal'])
g.loc[idx[:, 'dog'], :] # <--- WORKS because 'dog' is an element of level 1.
But...
g = df[df['Label']=='A].groupby(['Label', 'Animal']).agg('sum')
g.index
>>> MultiIndex([('A', 'cat')],
names=['Label', 'Animal'])
g.loc[idx[:, 'dog'], :] # <--- KeyError because 'dog' is NOT an element of level 1.
The docs for Index.reindex don't mention the level argument or give any examples, the docs for DataFrame.reindex were better but still not actually consistent with the arguments and no multiindex examples. And I tried to find any relevant parts of the guide which deal with reindexing multi indexes but without success.
Now that Indexing with missing keys returns a KeyError is it more important to provide example for these issues? Or have I missed something very simple.
The text was updated successfully, but these errors were encountered:
I have checked that this issue has not already been reported.
I have confirmed this bug exists on the latest version of pandas.
(optional) I have confirmed this bug exists on the master branch of pandas.
This is about trying to reindex a MultiIndex level to add keys to avoid a
KeyError
.This code could be more minimalist and more generic but the context in which the error arose might be helpful..
When using
groupby
unnecessary keys are eliminated..But...
I tried to solve this with
The docs for
Index.reindex
don't mention thelevel
argument or give any examples, the docs forDataFrame.reindex
were better but still not actually consistent with the arguments and no multiindex examples. And I tried to find any relevant parts of the guide which deal with reindexing multi indexes but without success.Now that Indexing with missing keys returns a
KeyError
is it more important to provide example for these issues? Or have I missed something very simple.The text was updated successfully, but these errors were encountered: