Skip to content

BUG: Error in apply operation on groupby if subset of columns are selected #42899

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
2 of 3 tasks
digital-idiot opened this issue Aug 5, 2021 · 1 comment
Closed
2 of 3 tasks
Labels
Duplicate Report Duplicate issue or pull request

Comments

@digital-idiot
Copy link

digital-idiot commented Aug 5, 2021

  • 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.


Code Sample, a copy-pastable example

import numpy as np
import pandas as pd
rand = np.random.RandomState(1)
df = pd.DataFrame(
    {
        'A': ['foo', 'bar'] * 3,
        'B': rand.randn(6),
        'C': rand.randint(0, 20, 6)
    }
)
gb = df.groupby(['A', 'C'])
x = gb.apply(pd.DataFrame.to_numpy).tolist()  # This works 
y = gb[['B', 'C']].apply(pd.DataFrame.to_numpy).tolist()  # This does not work

Problem description

In the snippet above x works and contains list of arrays as expected. In the next line, selecting subset of columns in the DataFrameGroupBy object then performing the same operations should also work as expected. However, y raises following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~/.conda/envs/PyDev/lib/python3.9/site-packages/pandas/core/groupby/groupby.py in apply(self, func, *args, **kwargs)
   1252             try:
-> 1253                 result = self._python_apply_general(f, self._selected_obj)
   1254             except TypeError:

~/.conda/envs/PyDev/lib/python3.9/site-packages/pandas/core/groupby/groupby.py in _python_apply_general(self, f, data)
   1288 
-> 1289         return self._wrap_applied_output(
   1290             data, keys, values, not_indexed_same=mutated or self.mutated

~/.conda/envs/PyDev/lib/python3.9/site-packages/pandas/core/groupby/generic.py in _wrap_applied_output(self, data, keys, values, not_indexed_same)
   1166             #  after raising AttributeError above
-> 1167             return self.obj._constructor_sliced(
   1168                 values, index=key_index, name=self._selection

~/.conda/envs/PyDev/lib/python3.9/site-packages/pandas/core/series.py in __init__(self, data, index, dtype, name, copy, fastpath)
    352 
--> 353             name = ibase.maybe_extract_name(name, data, type(self))
    354 

~/.conda/envs/PyDev/lib/python3.9/site-packages/pandas/core/indexes/base.py in maybe_extract_name(name, obj, cls)
   6392     if not is_hashable(name):
-> 6393         raise TypeError(f"{cls.__name__}.name must be a hashable type")
   6394 

TypeError: Series.name must be a hashable type

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-1-d8f27e6031fe> in <module>
     11 gb = df.groupby(['A', 'C'])
     12 x = gb.apply(pd.DataFrame.to_numpy).tolist()
---> 13 y = gb[['B', 'C']].apply(pd.DataFrame.to_numpy).tolist()

~/.conda/envs/PyDev/lib/python3.9/site-packages/pandas/core/groupby/groupby.py in apply(self, func, *args, **kwargs)
   1262 
   1263                 with group_selection_context(self):
-> 1264                     return self._python_apply_general(f, self._selected_obj)
   1265 
   1266         return result

~/.conda/envs/PyDev/lib/python3.9/site-packages/pandas/core/groupby/groupby.py in _python_apply_general(self, f, data)
   1287         keys, values, mutated = self.grouper.apply(f, data, self.axis)
   1288 
-> 1289         return self._wrap_applied_output(
   1290             data, keys, values, not_indexed_same=mutated or self.mutated
   1291         )

~/.conda/envs/PyDev/lib/python3.9/site-packages/pandas/core/groupby/generic.py in _wrap_applied_output(self, data, keys, values, not_indexed_same)
   1165             # TODO: sure this is right?  we used to do this
   1166             #  after raising AttributeError above
-> 1167             return self.obj._constructor_sliced(
   1168                 values, index=key_index, name=self._selection
   1169             )

~/.conda/envs/PyDev/lib/python3.9/site-packages/pandas/core/series.py in __init__(self, data, index, dtype, name, copy, fastpath)
    351         else:
    352 
--> 353             name = ibase.maybe_extract_name(name, data, type(self))
    354 
    355             if is_empty_data(data) and dtype is None:

~/.conda/envs/PyDev/lib/python3.9/site-packages/pandas/core/indexes/base.py in maybe_extract_name(name, obj, cls)
   6391     # GH#29069
   6392     if not is_hashable(name):
-> 6393         raise TypeError(f"{cls.__name__}.name must be a hashable type")
   6394 
   6395     return name

TypeError: Series.name must be a hashable type

Expected Output

y would be a list of array containing only selected columns (as specified).

Related issues

#18930

Output of pd.show_versions()

INSTALLED VERSIONS

commit : f00ed8f
python : 3.9.6.final.0
python-bits : 64
OS : Linux
OS-release : 5.13.5-1-MANJARO
Version : #1 SMP PREEMPT Mon Jul 26 07:43:29 UTC 2021
machine : x86_64
processor :
byteorder : little
LC_ALL : None
LANG : en_US.utf8
LOCALE : en_US.UTF-8

pandas : 1.3.0
numpy : 1.20.3
pytz : 2021.1
dateutil : 2.8.2
pip : 21.2.2
setuptools : 52.0.0.post20210125
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.0.1
IPython : 7.26.0
pandas_datareader: None
bs4 : None
bottleneck : 1.3.2
fsspec : 2021.07.0
fastparquet : None
gcsfs : None
matplotlib : None
numexpr : 2.7.3
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : 1.7.0
sqlalchemy : None
tables : None
tabulate : None
xarray : 0.19.0
xlrd : None
xlwt : None
numba : 0.53.1

@digital-idiot digital-idiot added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Aug 5, 2021
@phofl
Copy link
Member

phofl commented Aug 10, 2021

Hi, thanks for your report. As you mentioned this related repsectively a duplicate of #18930

@phofl phofl added Duplicate Report Duplicate issue or pull request and removed Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Aug 10, 2021
@phofl phofl closed this as completed Aug 10, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate Report Duplicate issue or pull request
Projects
None yet
Development

No branches or pull requests

2 participants