Skip to content

The groupby filter output differs if we run an aggregate function before #17091

Closed
@arnaudlegout

Description

@arnaudlegout

Code Sample, a copy-pastable example if possible

# I create a test DataFrame
d = pd.DataFrame({'data': range(6), 'key': list('ABCABC')})
# I groupby the column 'key'
g = d.groupby('key')
# I filter with always True (not that useful, just for the example)
print(g.filter(lambda x: True))
g.sum()
print(g.filter(lambda x: True))

Problem description

Here is the output of the above code

   data key
0     0   A
1     1   B
2     2   C
3     3   A
4     4   B
5     5   C
   data
0     0
1     1
2     2
3     3
4     4
5     5

I don't understand why the column key is in the output in the first run of filter, whereas when running an aggregate function (here g.sum()) before the filter, the key column disappear. If I use the as_index=False for the groupby, then the column is correctly preserved (as expected).

It looks like the aggregate function somehow change the groupby object, whereas my understanding of the groupby object is that each function call return a new object (and do not modify the original groupby object).

Expected Output

   data key
0     0   A
1     1   B
2     2   C
3     3   A
4     4   B
5     5   C

   data key
0     0   A
1     1   B
2     2   C
3     3   A
4     4   B
5     5   C

Output of pd.show_versions()

INSTALLED VERSIONS ------------------ commit: None python: 3.6.1.final.0 python-bits: 64 OS: Windows OS-release: 10 machine: AMD64 processor: Intel64 Family 6 Model 69 Stepping 1, GenuineIntel byteorder: little LC_ALL: None LANG: None LOCALE: None.None

pandas: 0.20.2
pytest: None
pip: 9.0.1
setuptools: 27.2.0
Cython: None
numpy: 1.13.1
scipy: 0.19.1
xarray: None
IPython: 6.1.0
sphinx: None
patsy: None
dateutil: 2.6.0
pytz: 2017.2
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 2.0.2
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: 0.999
sqlalchemy: 1.1.11
pymysql: None
psycopg2: None
jinja2: 2.9.6
s3fs: None
pandas_gbq: None
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions