pandas DataFrame with non-integer index and groupby apply

Viewed 305

I have the following DataFrame with non-integer index:

df = pd.DataFrame(index=[1.0,1.4,2,2.5], data={'a': ['a','b','a','b']})

     a
1.0  a
1.4  b
2.0  a
2.5  b

When I do

df.groupby('a').apply(lambda x: 42)

I get the following exception:

Traceback (most recent call last):
  File "/opt/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 2895, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas/_libs/index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 386, in pandas._libs.hashtable.Float64HashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 393, in pandas._libs.hashtable.Float64HashTable.get_item
KeyError: 0.0

If I reset_index() before grouping, I get the expected result:

df.reset_index().groupby('a').apply(lambda x: 42)

Out[130]: 
a
a    42
b    42
dtype: int64

How can I group and apply a function to the groups without having to reset the index?

For what it's worth, I use pandas 1.1.3.

0 Answers
Related