BUG: future_stack changes incorrectly pd.NA in index to np.nan · Issue #56573 · pandas-dev/pandas (original) (raw)
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 numpy as np df = pd.DataFrame([[1]], index=[pd.NA], columns=["c1"])
df.stack(future_stack=True) # returns incorrectly 'NaN c1 1'
df.stack(future_stack=False) # returns correctly ' c1 1'
Issue Description
If dataframe index holds pd.NA
value then df.stack(future_stack=True)
returns result with np.nan
.
It's different behavior then df.stack(future_stack=False)
.
After some digging I found out this could be the solution:
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index 8c822ec58e..5fb5e7e02e 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -954,7 +954,7 @@ def stack_v3(frame: DataFrame, level: list[int]) -> Series | DataFrame:
index_codes = list(np.tile(frame.index.codes, (1, ratio)))
else:
index_levels = [frame.index.unique()]
- codes = factorize(frame.index)[0]
+ codes = factorize(frame.index, use_na_sentinel=False)[0]
index_codes = list(np.tile(codes, (1, ratio)))
if isinstance(stack_cols, MultiIndex):
column_levels = ordered_stack_cols.levels
Expected Behavior
df.stack(future_stack=True)
should return the same result as df.stack(future_stack=False)
.
Installed Versions
INSTALLED VERSIONS
commit : a671b5a
python : 3.11.6.final.0
python-bits : 64
OS : Darwin
OS-release : 22.5.0
Version : Darwin Kernel Version 22.5.0: Thu Jun 8 22:22:20 PDT 2023; root:xnu-8796.121.3~7/RELEASE_ARM64_T6000
machine : arm64
processor : arm
byteorder : little
LC_ALL : None
LANG : None
LOCALE : en_GB.UTF-8
pandas : 2.1.4
numpy : 1.26.2
pytz : 2023.3.post1
dateutil : 2.8.2
setuptools : 69.0.2
pip : 23.3.1
Cython : 0.29.36
pytest : 7.4.3
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : None
pandas_datareader : None
bs4 : None
bottleneck : None
dataframe-api-compat: None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : 13.0.0
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None