Skip to content

groupby(group_keys=True) ignored when apply returns unsliced data #8467

Closed
@kay1793

Description

@kay1793

I ran into this unexplained behaviour with groupby when using group_keys=True (the default),
it's not clear why using x vs. x[:] causes the group_keys argument to be ignored.

In [86]: df = DataFrame({'key': [1, 1, 1, 2, 2, 2, 3, 3, 3],
    ...:                 'value': range(9)})
    ...: df
Out[86]: 
   key  value
0    1      0
1    1      1
2    1      2
3    2      3
4    2      4
5    2      5
6    3      6
7    3      7
8    3      8

In [87]: df.groupby('key', group_keys=True).apply(lambda x: x[:].key)
Out[87]: 
key   
1    0    1
     1    1
     2    1
2    3    2
     4    2
     5    2
3    6    3
     7    3
     8    3
Name: key, dtype: int64

In [88]: df.groupby('key', group_keys=True).apply(lambda x: x.key)
Out[88]: 
0    1
1    1
2    1
3    2
4    2
5    2
6    3
7    3
8    3
Name: key, dtype: int64

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions