Skip to content

BUG: RollingGroupby.corr() producing incorrect results #43386

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
2 of 3 tasks
grantgustafson opened this issue Sep 3, 2021 · 3 comments · Fixed by #43854
Closed
2 of 3 tasks

BUG: RollingGroupby.corr() producing incorrect results #43386

grantgustafson opened this issue Sep 3, 2021 · 3 comments · Fixed by #43854
Labels
Bug Groupby Regression Functionality that used to work in a prior pandas version Window rolling, ewma, expanding
Milestone

Comments

@grantgustafson
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.


Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.

Code Sample, a copy-pastable example

import pandas as pd                                                                                                                                                                                          
# sample dataframe. We order it by column c                                                                                                                                                                                                    
df = pd.DataFrame({                                                                                                                                                                                          
    "a": ["g1"]*4 + ["g2"]*4,                                                                                                                                                                                
    "b": range(8),                                                                                                                                                                                           
    "c": [0, 4, 6, 1, 2, 7, 3, 5]                                                                                                                                                                            
}).sort_values("c")                                                                                                                                                                                          
df                                                                                                                                                                                                           
a b c
0 g1 0 0
3 g1 3 1
4 g2 4 2
6 g2 6 3
1 g1 1 4
7 g2 7 5
2 g1 2 6
5 g2 5 7
(df.groupby("a")[["b", "c"]]
        .rolling(3)
        .corr()
        .unstack()
        .iloc[:, 1]
        .droplevel("a")
        .sort_index())
0         NaN
1         NaN
2    0.155543
3         NaN
4    0.960769
5   -0.397360
6    0.981981
7         NaN
Name: (b, c), dtype: float64
# this result should be no different than above - sorting by groupby key should not be necessary
(df.sort_values(["a", "c"]).groupby("a")[["b", "c"]]
        .rolling(3)
        .corr()
        .unstack()
        .iloc[:, 1]
        .droplevel("a")
        .sort_index())
0         NaN
1    0.052414
2   -0.596040
3         NaN
4         NaN
5   -0.500000
6         NaN
7    0.928571
Name: (b, c), dtype: float64

Problem description

This RollingGroupby.corr() operation is producing incorrect results. The example above shows how sorting the dataframe with respect to the groupby key fixes the issue, but that should not be necessary since it is the groupby key. I have tested and this bug does not exist in version 1.2.5. It first appears in 1.3.0.

Expected Output

The bottom part of the above repro contains expected output. Here's another way of showing expected output by filtering to one group:

(df[df['a'] == "g1"]
        .groupby("a")[["b", "c"]]
        .rolling(3)
        .corr()
        .unstack()
        .iloc[:, 1]
        .droplevel("a")
        .sort_index())
0         NaN
1    0.052414
2   -0.596040
3         NaN
Name: (b, c), dtype: float64

Output of pd.show_versions()

INSTALLED VERSIONS

commit : 5f648bf
python : 3.8.10.final.0
python-bits : 64
OS : Linux
OS-release : 4.18.0-240.22.1.el8_3.x86_64
Version : #1 SMP Thu Mar 25 14:36:04 EDT 2021
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.3.2
numpy : 1.21.2
pytz : 2021.1
dateutil : 2.8.2
pip : 21.2.4
setuptools : 57.4.0
Cython : None
pytest : 6.2.5
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.0.1
IPython : 7.27.0
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : 0.8.7
fastparquet : None
gcsfs : None
matplotlib : 3.4.3
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : 5.0.0
pyxlsb : None
s3fs : 0.4.2
scipy : 1.7.1
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : 2.0.1
xlwt : None
numba : None

@grantgustafson grantgustafson added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 3, 2021
@simonjayhawkins
Copy link
Member

Thanks @grantgustafson for the report. can you update the code sample with a minimum reproducible example https://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports

AFAICT with just a quick look the problem is maybe with the rolling step.

code sample (not yet minimal) with some "debug"

print(pd.__version__)

df = pd.DataFrame(
    {"a": ["g1"] * 4 + ["g2"] * 4, "b": range(8), "c": [0, 4, 6, 1, 2, 7, 3, 5]}
).sort_values("c")
grp = df.groupby("a")[["b", "c"]].rolling(3)
for _df in grp:
    print(_df)
result = grp.corr()
print(result)
1.3.2
   b  c
0  0  0
   b  c
0  0  0
3  3  1
   b  c
0  0  0
3  3  1
4  1  4
   b  c
3  3  1
4  1  4
6  2  6
   b  c
1  4  2
   b  c
1  4  2
7  6  3
   b  c
1  4  2
7  6  3
2  7  5
   b  c
7  6  3
2  7  5
5  5  7
               b         c
a                         
g1 0 b       NaN       NaN
     c       NaN       NaN
   3 b       NaN       NaN
     c       NaN       NaN
   4 b  1.000000  0.960769
     c  0.960769  1.000000
   6 b  1.000000  0.981981
     c  0.981981  1.000000
g2 1 b       NaN       NaN
     c       NaN       NaN
   7 b       NaN       NaN
     c       NaN       NaN
   2 b  1.000000  0.155543
     c  0.155543  1.000000
   5 b  1.000000 -0.397360
     c -0.397360  1.000000
1.2.5
   b  c
0  0  0
   b  c
0  0  0
3  3  1
   b  c
0  0  0
3  3  1
1  1  4
   b  c
3  3  1
1  1  4
2  2  6
   b  c
4  4  2
   b  c
4  4  2
6  6  3
   b  c
4  4  2
6  6  3
7  7  5
   b  c
6  6  3
7  7  5
5  5  7
               b         c
a                         
g1 0 b       NaN       NaN
     c       NaN       NaN
   3 b       NaN       NaN
     c       NaN       NaN
   1 b  1.000000  0.052414
     c  0.052414  1.000000
   2 b  1.000000 -0.596040
     c -0.596040  1.000000
g2 4 b       NaN       NaN
     c       NaN       NaN
   6 b       NaN       NaN
     c       NaN       NaN
   7 b  1.000000  0.928571
     c  0.928571  1.000000
   5 b  1.000000 -0.500000
     c -0.500000  1.000000

@simonjayhawkins simonjayhawkins added Regression Functionality that used to work in a prior pandas version Window rolling, ewma, expanding and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 4, 2021
@simonjayhawkins simonjayhawkins added this to the 1.3.3 milestone Sep 4, 2021
simonjayhawkins added a commit to simonjayhawkins/pandas that referenced this issue Sep 4, 2021
@simonjayhawkins
Copy link
Member

I have tested and this bug does not exist in version 1.2.5. It first appears in 1.3.0

first bad commit: [b2671cc] PERF: Rolling/Expanding.cov/corr (#39591)

cc @mroeschke

also xref #42915 which is a grouping issue.

@grantgustafson
Copy link
Author

grantgustafson commented Sep 5, 2021

Thanks @grantgustafson for the report. can you update the code sample with a minimum reproducible example https://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports

Hi @simonjayhawkins, my example is as minimum of a repro that I can currently produce. Since it requires multiple groups and a rolling window, I hit a soft-floor. I don't doubt it can be made more concise though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Groupby Regression Functionality that used to work in a prior pandas version Window rolling, ewma, expanding
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants