Skip to content

BUG: groupby rolling apply giving strange index #49878

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

Open
3 tasks done
fakio opened this issue Nov 23, 2022 · 9 comments
Open
3 tasks done

BUG: groupby rolling apply giving strange index #49878

fakio opened this issue Nov 23, 2022 · 9 comments
Labels
Apply Apply, Aggregate, Transform, Map Bug Groupby Window rolling, ewma, expanding

Comments

@fakio
Copy link

fakio commented Nov 23, 2022

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd
import datetime

d = pd.DataFrame([
    (datetime.date(2022, 1, 1), 'A', 10),
    (datetime.date(2022, 1, 2), 'B', 20),
    (datetime.date(2022, 1, 3), 'A', 30),
    (datetime.date(2022, 1, 4), 'B', 40),
],
columns=['date','group','value'])

d['date'] = pd.to_datetime(d['date'])

def func(s):
    print(s)
    return s.index.max().day

d.set_index(d.date).groupby('group').rolling('7d').value.apply(func)

Issue Description

I'm trying to apply a custom function using rolling apply and using the date index of the window, but the index of the data passed to the apply function seems incorrect

output of above rolling apply:

group  date      
A      2022-01-01    1.0
       2022-01-03    2.0
B      2022-01-02    3.0
       2022-01-04    4.0
Name: value, dtype: float64

Expected Behavior

group  date      
A      2022-01-01    1.0
       2022-01-03    3.0
B      2022-01-02    2.0
       2022-01-04    4.0
Name: value, dtype: float64

Installed Versions

INSTALLED VERSIONS

commit : 8dab54d
python : 3.8.10.final.0
python-bits : 64
OS : Linux
OS-release : 5.15.0-52-generic
Version : #58~20.04.1-Ubuntu SMP Thu Oct 13 13:09:46 UTC 2022
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : pt_BR.UTF-8

pandas : 1.5.2
numpy : 1.22.3
pytz : 2021.3
dateutil : 2.8.2
setuptools : 45.2.0
pip : 22.3.1
Cython : None
pytest : 4.6.9
hypothesis : None
sphinx : 4.4.0
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.9.1
html5lib : 1.0.1
pymysql : 1.0.2
psycopg2 : None
jinja2 : 3.1.2
IPython : 7.13.0
pandas_datareader: None
bs4 : 4.8.2
bottleneck : None
brotli : 1.0.9
fastparquet : None
fsspec : 2022.11.0
gcsfs : None
matplotlib : 3.6.0
numba : 0.56.4
numexpr : 2.7.1
odfpy : None
openpyxl : 3.0.3
pandas_gbq : None
pyarrow : 7.0.0
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.3.3
snappy : None
sqlalchemy : None
tables : 3.6.1
tabulate : 0.8.9
xarray : None
xlrd : 1.1.0
xlwt : 1.3.0
zstandard : None
tzdata : None

@fakio fakio added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Nov 23, 2022
@fakio
Copy link
Author

fakio commented Nov 24, 2022

maybe related to #48056

@fakio
Copy link
Author

fakio commented Nov 27, 2022

seems related to #47494 and #45925 too @mroeschke

@mroeschke
Copy link
Member

mroeschke commented Nov 29, 2022

I believe the resulting index is correct here but the values are ordered incorrectly. Investigation and pull requests welcome!

@mroeschke mroeschke added Groupby Apply Apply, Aggregate, Transform, Map Window rolling, ewma, expanding and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Nov 29, 2022
@fakio
Copy link
Author

fakio commented Dec 1, 2022

from what I could debug until now, in https://github.com/pandas-dev/pandas/blob/main/pandas/core/window/rolling.py#L1417, "values" is the original values reordered by groups and self._on is the original index, so the resulting Series has mismatched index/values.

@fakio
Copy link
Author

fakio commented Dec 3, 2022

@mroeschke, adding the code below right after https://github.com/pandas-dev/pandas/blob/main/pandas/core/window/rolling.py#L874 seems to fix my problem

self._on = obj.index

This code (https://github.com/pandas-dev/pandas/blob/main/pandas/core/window/rolling.py#L871) is reordering the values considering groups but later it is used with the index not ordered by groups (https://github.com/pandas-dev/pandas/blob/main/pandas/core/window/rolling.py#L1417). My code above set the index to the ordered by groups index.

But I have no idea if this is the right fix. It seems not.

@luke396
Copy link
Contributor

luke396 commented Apr 11, 2023

take

@luke396
Copy link
Contributor

luke396 commented Apr 12, 2023

Hi @mroeschke, I think the problem may be here.

def apply_func(values, begin, end, min_periods, raw=raw):
if not raw:
# GH 45912
values = Series(values, index=self._on, copy=False)
return window_func(values, begin, end, min_periods)
return apply_func

values is

2022-01-01    10.0
2022-01-02    30.0
2022-01-03    20.0
2022-01-04    40.0
dtype: float64

When window_func(values, begin, end, min_periods) will return [1, 2, 3, 4]. I think if it could return [1,3,2,4], and bug will be fixed.

I want to confirm that values like this is indeed what we want? If so, seems we need to find a way reindex [1,2,3,4] in following codes.

@luke396
Copy link
Contributor

luke396 commented Apr 16, 2023

This is a more concise failure case.

import pandas as pd
def f(x):
    return x.index.values
df = pd.DataFrame([(1, 10, 'A'), (2, 15, 'B'), (3, 20, 'A')],
                  columns=['idx', 'value', 'group']).set_index('idx')
gb = df.groupby('group')
gbr = gb.rolling(1)

# list(gbr)  # in right order
gbr.apply(f)  #  wrong
#           value
# group idx       
# A     1      1.0
#       3      2.0
# B     2      3.0

@luke396
Copy link
Contributor

luke396 commented Apr 16, 2023

I want to confirm that values like this is indeed what we want? If so, seems we need to find a way reindex [1,2,3,4] in following codes.

I apologize for providing incorrect information earlier. Upon further examination, it appears that the values is correct. However, I believe that the issue stems from these lines of code:

def apply_func(values, begin, end, min_periods, raw=raw):
if not raw:
# GH 45912
values = Series(values, index=self._on, copy=False)
return window_func(values, begin, end, min_periods)
return apply_func

In the apply_fun function, we accept the values variable, which contains the groupby value, and set the index with the original index. We then pass this, along with two pointers (begin/end), to window_aggregations.roll_apply. We use the pointers to slice the index and call the UDF. However, this UDF attempts to find the groupbyObject's index, which we do not pass to it. It seems that we assume that no one will want to operate on it, so we only pass in the groupbyObject's value and use the groupbyObject's index to reindex the output.

I have two ideas for solving this issue. The first is to add some documentation to inform users not to attempt to get some from groupbyObject's index. If they do need, they should create a copy and add a new column. The second idea is to find a way to add some information about the modified groupbyObject index.

Please let me know if you have any advice or if I have misunderstood anything. politely cc @mroeschke

@luke396 luke396 removed their assignment Mar 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Apply Apply, Aggregate, Transform, Map Bug Groupby Window rolling, ewma, expanding
Projects
None yet
Development

No branches or pull requests

3 participants