BUG: `dropna` affects `observed` in `DataFrame.groupby()` since v1.5

This issue has been created since 2022-09-19.

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

# With pandas 1.5

from pandas import DataFrame, Categorical

df = DataFrame({"x": Categorical([1, 2], categories=[1, 2, 3]), "y": [3, 4]})

df.groupby("x", observed=False).grouper.result_index
# CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=False, dtype='category', name='x')

df.groupby("x", observed=False, dropna=False).grouper.result_index
# CategoricalIndex([1, 2], categories=[1, 2, 3], ordered=False, dtype='category', name='x')
# ------------------------------------------------------------------------------------------
# Unexpected result ↑

df.groupby("x", observed=False, dropna=True).grouper.result_index
# CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=False, dtype='category', name='x')


# With pandas 1.4.4 and prior

df.groupby("x", observed=False).grouper.result_index
# CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=False, dtype='category', name='x')

df.groupby("x", observed=False, dropna=False).grouper.result_index
# CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=False, dtype='category', name='x')

df.groupby("x", observed=False, dropna=True).grouper.result_index
# CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=False, dtype='category', name='x')

Issue Description

dropna=False in DataFrame.groupby() should not affect the results when observed=False.

Expected Behavior

Expected the behavior with pandas 1.4.4 and prior.

Installed Versions

INSTALLED VERSIONS

commit : 87cfe4e
python : 3.9.5.final.0
python-bits : 64
OS : Linux
OS-release : 5.15.57.1-microsoft-standard-WSL2
Version : #1 SMP Wed Jul 27 02:20:31 UTC 2022
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : C.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.5.0
numpy : 1.23.3
pytz : 2022.1
dateutil : 2.8.2
setuptools : 58.0.0
pip : 22.2.2
Cython : None
pytest : 6.2.5
hypothesis : None
sphinx : 4.5.0
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.6.3
html5lib : 1.1
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.1.1
pandas_datareader: None
bs4 : 4.9.3
bottleneck : None
brotli :
fastparquet : None
fsspec : 2022.02.0
gcsfs : None
matplotlib : 3.5.1
numba : 0.53.1
numexpr : None
odfpy : None
openpyxl : 3.0.8
pandas_gbq : None
pyarrow : 7.0.0
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.8.0
snappy : None
sqlalchemy : 1.4.28
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
zstandard : None
tzdata : None

phofl wrote this answer on 2022-09-19

cc @rhshadrach

Confirmed:

56a71845decdc308d4210d74c7a59e42f0762c31 is the first bad commit
commit 56a71845decdc308d4210d74c7a59e42f0762c31
Author: Richard Shadrach <[email protected]>
Date:   Thu Aug 18 12:09:09 2022 -0400

    BUG: algorithms.factorize moves null values when sort=False (#46601)

#46601

rhshadrach wrote this answer on 2022-09-21

#46601 fixed an issue with dropna and categorical, namely dropna with categorical still drops null values. On 1.4.x:

values, dtype = (["y", None, "x", "y"], "category")
key = pd.Series(values, dtype=dtype)
df = pd.DataFrame({"key": key, "a": [1, 2, 3, 4]})
gb = df.groupby("key", dropna=False)
print(gb.sum())

#      a
# key   
# x    3
# y    5

The null value is included in the result on 1.5.0. As identified, the patch did not correctly implement the case where observed=False.

I've looked into this, and it appears to me our current implementation of categorical with nulls and dropna are incompatible in groupby. Namely, categorical encodes values as nonnegative integers with nulls being represented by -1 while groupby with dropna=False requires nulls be encoded by nonnegative integers.

We could maybe hack in a patch where we add the null value(s?) to the categories only to remove them upon returning the result. This seems like it would be too significant of a change for a patch release, fragile, and prone to bugs. I am wondering if a better direction I think would be to reimplement groupby so that negative codes are only dropped when dropna=True. This may have some drawbacks and would need some experimenting, but again, too large of a change for a patch version in my opinion.

With this, my recommendation is to undo the offending line from #46601, i.e. change

if self._dropna and self._passed_categorical:

to become if self._passed_categorical:. This would make it so that dropna=False does not work with categorical again, but fixing this regression. I will put up a PR for this, but wanted to see if others have any thoughts first.

cc @jbrockmendel @mroeschke @jreback @phofl @jorisvandenbossche

More Details About Repo
Owner Name pandas-dev
Repo Name pandas
Full Name pandas-dev/pandas
Language Python
Created Date 2010-08-24
Updated Date 2022-09-29
Star Count 35374
Watcher Count 1122
Fork Count 15034
Issue Count 3579

YOU MAY BE INTERESTED

Issue Title Created Date Comment Count Updated Date
Main_Validation color 3 2022-01-01 2022-09-23
UTF-8 characters in subprocess output make `kraft configure` crash 1 2022-02-09 2022-08-08
Extruder filament widget not working correctly 14 2021-11-07 2022-09-15
Invoke-DcnRepairClone: Drop broken clones 1 2022-06-27 2022-09-26
Cannot build with Go 1.18 on darwin/arm64 0 2022-03-31 2022-09-03
[FEATURE] Translating safety properties to trace invariants 0 2022-02-02 2022-02-06
TL-WDR4300-v1 builds seem to be failing 3 2020-12-03 2022-07-25
Use stable clang-tidy 0 2022-08-12 2022-09-15
HTML on the start-page is not shown as HTML 5 2022-04-23 2022-08-21
No audio with remote server added. 3 2021-01-02 2022-08-29
Potential memory leak 0 2021-12-23 2022-09-14
ExporerPatcher 1 2021-10-28 2021-11-13
how do I pad "wide" values on x axis, like histogram charts etc? 0 2021-05-02 2022-09-21
maintner: Tombstoned Issues 1 2019-10-16 2022-09-28
[DOC] "rapids_cuda_init_runtime" docs missing 0 2021-10-19 2022-09-14
Change format indent length? 2 2022-01-05 2022-08-31
UNPKG error: `Cannot find "/index.js" in [email protected]` 2 2021-09-07 2022-09-24
macOS Monterey: unable to use Finder Integration 1 2021-11-10 2022-09-18
Support jump hosts in the SSH connector 2 2022-04-08 2022-07-20
033-traits::constructの戻り値について 1 2020-01-09 2022-09-02
First attempt with starting app always fails 11 2020-08-23 2022-02-08
The assignments submissions are null in c# call 3 2022-08-12 2022-09-12
Creating a one-on-one chat using user principal name fails with error Failed to find users with user principal name 2 2022-08-10 2022-09-12
AWS CloudWatch Logs: Additional supported log retention options 0 2022-05-13 2022-09-10
Has the library given up updating? 10 2020-06-04 2022-09-21
Add a resetDefault prop to SelectedFilters components to reset filters back to their default values 1 2021-06-18 2022-09-10
[feature]: When importing a postman collection, don't automatically add `http://` 2 2022-03-27 2022-09-20
Server error when reporting a proposal that comes from a meeting as inappropriate 1 2021-11-26 2022-09-05
Select skills to import from the catalog, then change pages and the selected skills are not imported 2 2022-01-18 2022-09-15
Regenerate registration file based on new config changes 2 2021-02-24 2022-07-31
Android App crash instantly after add Realm + React Navigation Drawer (screens/gesture handler/hermes) 5 2022-02-02 2022-09-19
Add cake-contrib user 1 2019-07-25 2022-03-23
aya: Support TC-style map definitions 10 2022-01-12 2022-09-02
Undefined behavior in point_cloud.h 3 2021-06-30 2022-08-19
Creating .alist files. 2 2021-08-12 2022-09-17
Message Status Indicator not working consistently in (Azure communication services the UI Library) for chat 6 2022-07-08 2022-09-21
Dynamically Set the picker as not editable 0 2022-05-14 2022-09-21
Foldings received a StackOverflowError while scanning the document 5 2021-06-29 2022-09-08
How to add HarnessBinder with more ports 3 2022-02-03 2022-08-21
打开web页面的时候总是提示error happened when setup websocket 3 2017-03-20 2022-09-19
[SPARK-39469][SQL] Infer date type for CSV schema inference 0 2022-07-25 2022-07-24
Autostart applications minmized 1 2020-01-11 2022-09-24
"No Title" posts confuse the interface 3 2022-06-20 2022-09-20
Update entity dialog doesn't change when the update is finished 3 2022-05-04 2022-09-03
Cannot train due to missing labels 0 2021-07-03 2022-09-17
[Bug] jdbc / beeline client can not exit when engine error 4 2022-09-01 2022-09-15
Customizable 404 page 0 2021-02-22 2022-09-14
indicator:Confidence missing after importing STIX1.1.1/2.0 files into MISP 0 2021-09-14 2022-09-11
form-control-focus mixin error 0 2017-09-22 2022-09-14
Delete registered client 3 2021-11-02 2022-08-29