BUG: replace method with np.nan produces incorrect results · Issue #46306 · 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({'A': [0, 1, 2], 'B': [1, 0, 2]}) df.replace({0:1, 1:np.nan})
Issue Description
Pandas 1.4 changed the way the replace method works:
pandas 1.3.4:df
A B
0 0 1
1 1 0
2 2 2df.replace({0:1, 1:np.nan})
A B
0 1.0 NaN
1 NaN 1.0
2 2.0 2.0
pandas 1.4.1:df
A B
0 0 1
1 1 0
2 2 2df.replace({0:1, 1:np.nan})
A B
0 NaN NaN
1 NaN NaN
2 2.0 2.0
As you can see with the latest version first value 0 was replaced to 1 and then existing '1' and the new from replaced 0 were replaced to nan.
However, the same replacement using other values then np.nan works ok, for instance:df.replace({0:1, 1:10})
A B
0 1 10
1 10 1
2 2 2
Expected Behavior
It should work the same way as in version 1.3.
Installed Versions
INSTALLED VERSIONS
commit : bb1f651
python : 3.9.1.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.14393
machine : AMD64
processor : Intel64 Family 6 Model 79 Stepping 0, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_United States.1252
pandas : 1.4.0
numpy : 1.22.2
pytz : 2021.3
dateutil : 2.8.2
pip : 20.2.3
setuptools : 49.2.1
Cython : None
pytest : 7.0.0
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
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : 3.0.9
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : 2.0.1
xlwt : None
zstandard : None