Skip to content

BUG: Same function calls on the same DataFrameGroupBy object give different results #34271

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
1 of 3 tasks
leetschau opened this issue May 20, 2020 · 5 comments · Fixed by #35314
Closed
1 of 3 tasks
Assignees
Milestone

Comments

@leetschau
Copy link

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

Source codes

import pandas as pd                                    
inp = pd.DataFrame([[1, 2, 3, 4],
                    [5, 6, 7, 8],
                    [1, 10, 11, 12],
                    [5, 14, 15, 16],
                    [1, 18, 19, 20],
                    [21, 22, 23, 24],
                    [5, 26, 27, 28]],
                columns=['group', 'fa', 'fb', 'fc'])
print('pandas version:', pd.__version__)
grps = inp.groupby('group', as_index=True)
print('Column number in all groups:',
    grps.apply(lambda x: x.shape[1]).unique())
print('Column number in all groups:',
    grps.apply(lambda x: x.shape[1]).unique())
print('ID:', id(grps))
print('Shape of first dataframe in the group:', grps.first().shape)
print('ID:', id(grps))
print('Column number in all groups:',
    grps.apply(lambda x: x.shape[1]).unique())

Problem description

In above codes, same function calls grps.apply(lambda x: x.shape[1]).unique() give different results:

In the first 2 times before grps.first().shape is called, it returns 4.
While after grps.first().shape is called, it returns 3.

Running output

Column number in all groups: [4]
Column number in all groups: [4]
ID: 140686222651664
Shape of first dataframe in the group: (3, 3)
ID: 140686222651664
Column number in all groups: [3]

Expected Output

Column number in all groups: [4]
Column number in all groups: [4]
ID: 140686222651664
Shape of first dataframe in the group: (3, 3)
ID: 140686222651664
Column number in all groups: [4]

Environments

Python 3.7.7, Ubuntu 18.04.

Output of pd.show_versions():

INSTALLED VERSIONS
------------------
commit           : None
python           : 3.7.7.final.0
python-bits      : 64
OS               : Linux
OS-release       : 4.15.0-96-generic
machine          : x86_64
processor        : x86_64
byteorder        : little
LC_ALL           : en_US.UTF-8
LANG             : en_US.UTF-8
LOCALE           : en_US.UTF-8

pandas           : 1.0.2
numpy            : 1.18.1
pytz             : 2019.3
dateutil         : 2.8.1
pip              : 20.1
setuptools       : 41.2.0
Cython           : None
pytest           : None
hypothesis       : None
sphinx           : None
blosc            : None
feather          : None
xlsxwriter       : None
lxml.etree       : None
html5lib         : None
pymysql          : None
psycopg2         : None
jinja2           : None
IPython          : 7.13.0
pandas_datareader: None
bs4              : None
bottleneck       : None
fastparquet      : None
gcsfs            : None
lxml.etree       : None
matplotlib       : None
numexpr          : None
odfpy            : None
openpyxl         : None
pandas_gbq       : None
pyarrow          : None
pytables         : None
pytest           : None
pyxlsb           : None
s3fs             : None
scipy            : None
sqlalchemy       : None
tables           : None
tabulate         : None
xarray           : None
xlrd             : None
xlwt             : None
xlsxwriter       : None
numba            : None
@leetschau leetschau added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels May 20, 2020
@sharon0621
Copy link

come across the same question as yours

@charlesdong1991 charlesdong1991 added Apply Apply, Aggregate, Transform, Map and removed Needs Triage Issue that has not been reviewed by a pandas team member labels May 20, 2020
@manasjoshi14
Copy link

manasjoshi14 commented May 23, 2020

Confirmed on Ubuntu 18.04, Python 3.8.2, Pandas 1.0.3.

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

The issue lies in function "first()". It works inplace and modifies the GroubBy object removing the "group" column. Same happens with the function "nth".

I can take this if this is a bug and not by design.

@manasjoshi14
Copy link

manasjoshi14 commented May 25, 2020

Along with "first()", this seems to be an issue with the following functions as well:

@doc(_groupby_agg_method_template, fname="sum", no=True, mc=0)
def sum(self, numeric_only: bool = True, min_count: int = 0):
return self._agg_general(
numeric_only=numeric_only, min_count=min_count, alias="add", npfunc=np.sum
)
@doc(_groupby_agg_method_template, fname="prod", no=True, mc=0)
def prod(self, numeric_only: bool = True, min_count: int = 0):
return self._agg_general(
numeric_only=numeric_only, min_count=min_count, alias="prod", npfunc=np.prod
)
@doc(_groupby_agg_method_template, fname="min", no=False, mc=-1)
def min(self, numeric_only: bool = False, min_count: int = -1):
return self._agg_general(
numeric_only=numeric_only, min_count=min_count, alias="min", npfunc=np.min
)
@doc(_groupby_agg_method_template, fname="max", no=False, mc=-1)
def max(self, numeric_only: bool = False, min_count: int = -1):
return self._agg_general(
numeric_only=numeric_only, min_count=min_count, alias="max", npfunc=np.max
)
@doc(_groupby_agg_method_template, fname="first", no=False, mc=-1)
def first(self, numeric_only: bool = False, min_count: int = -1):
def first_compat(obj: FrameOrSeries, axis: int = 0):
def first(x: Series):
"""Helper function for first item that isn't NA.
"""
x = x.array[notna(x.array)]
if len(x) == 0:
return np.nan
return x[0]
if isinstance(obj, DataFrame):
return obj.apply(first, axis=axis)
elif isinstance(obj, Series):
return first(obj)
else:
raise TypeError(type(obj))
return self._agg_general(
numeric_only=numeric_only,
min_count=min_count,
alias="first",
npfunc=first_compat,
)
@doc(_groupby_agg_method_template, fname="last", no=False, mc=-1)
def last(self, numeric_only: bool = False, min_count: int = -1):
def last_compat(obj: FrameOrSeries, axis: int = 0):
def last(x: Series):
"""Helper function for last item that isn't NA.
"""
x = x.array[notna(x.array)]
if len(x) == 0:
return np.nan
return x[-1]
if isinstance(obj, DataFrame):
return obj.apply(last, axis=axis)
elif isinstance(obj, Series):
return last(obj)
else:
raise TypeError(type(obj))
return self._agg_general(
numeric_only=numeric_only,
min_count=min_count,
alias="last",
npfunc=last_compat,
)

@manasjoshi14
Copy link

The error occurs in the reset_cache call at :

self._reset_cache("_selected_obj")

which is a call to:

def _reset_cache(self, key: Optional[str] = None) -> None:

This seems to be too advanced for me to work on.

@smithto1
Copy link
Member

take

@jreback jreback added this to the 1.1 milestone Jul 17, 2020
@jreback jreback added Groupby and removed Apply Apply, Aggregate, Transform, Map labels Jul 17, 2020
@TomAugspurger TomAugspurger modified the milestones: 1.1, 1.1.1 Jul 28, 2020
@jreback jreback modified the milestones: 1.1.1, 1.2 Aug 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
7 participants