Skip to content

df.groupby() does not allow to use name of index at level 0 when not using a MultiIndex #4014

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
floux opened this issue Jun 24, 2013 · 2 comments · Fixed by #4015
Closed

Comments

@floux
Copy link

floux commented Jun 24, 2013

In [24]: df = pd.DataFrame({
   ....:         'exp' : ['A']*3 + ['B']*3,
   ....:         'var1' : range(6),
   ....:         })

In [25]: df = df.set_index(['exp'])

In [26]: df.index.names
Out[27]: ['exp']


In [28]: df
Out[28]:
     var1
exp
A       0
A       1
A       2
B       3
B       4
B       5

In [29]: try:
   ....:             df.groupby(level='exp').size()
   ....: except ValueError as e:
   ....:             print('index can not be accessed by name')
   ....:             print(e)
   ....:
index can not be accessed by name
level > 0 only valid with MultiIndex
# at this point I would argue that the level 'exp' is level 0,
# and therefore this should work.

In [29]: df1 = df.groupby(level=0).size()

In [30]: df1
Out[30]:
exp
A      3
B      3
dtype: int64
@hayd
Copy link
Contributor

hayd commented Jun 24, 2013

Good find. I've put a fix together for this (coming shortly).

Note: although in python 2 'exp' > 0 in py3 this raises an error.

@pepicello
Copy link
Contributor

Many years later, I have this issue with pandas 0.25.1, but with a different error. Small reproducible example:

pd.DataFrame([[1, 2], [3, 4]], columns=pd.Index(['a', 'b'], name='a')).groupby(level='a', axis=1)

which returns a ValueError: level name a is not the name of the index.

Is this behaviour expected? If it is, it would still be very handy to have a way to do this quickly on index names without needing to check if it is a MultiIndex before.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants