Skip to content

BUG pd.get_dummies does not propagate NaN correctly #15923

Open
@beckermr

Description

@beckermr

Code Sample, a copy-pastable example if possible

In [17]: s
Out[17]: 
0      a
1      b
2      c
3    NaN
dtype: object
In [18]: pd.get_dummies(s)
Out[18]: 
   a  b  c
0  1  0  0
1  0  1  0
2  0  0  1
3  0  0  0

Problem description

The current implementation does not propagate NaN correctly. NaN means the data is missing. So if you turn missing data to all zeros when one-hot encoding, you are asserting that the proper label is none of the labels you have. In reality, the proper label could be one of the labels you have, you just do not know the proper label.

I realize people use the dummy_na option here, but if that option is not passed, then the output should have the NaNs put in the right spot.

Expected Output

It should propagate the NaNs.

In [18]: pd.get_dummies(s)
Out[18]: 
   a  b  c
0  1  0  0
1  0  1  0
2  0  0  1
3  NaN  NaN  NaN

Output of pd.show_versions()

In [19]: pd.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.6.1.final.0
python-bits: 64
OS: Darwin
OS-release: 15.6.0
machine: x86_64
processor: i386
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.19.2
nose: 1.3.7
pip: 9.0.1
setuptools: 33.1.1.post20170320
Cython: 0.25.2
numpy: 1.12.1
scipy: 0.19.0
statsmodels: 0.8.0
xarray: None
IPython: 5.3.0
sphinx: None
patsy: 0.4.1
dateutil: 2.6.0
pytz: 2016.10
blosc: None
bottleneck: None
tables: 3.3.0
numexpr: 2.6.2
matplotlib: 2.0.0
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: 0.999
httplib2: None
apiclient: None
sqlalchemy: 1.1.5
pymysql: None
psycopg2: 2.6.2 (dt dec pq3 ext lo64)
jinja2: 2.9.5
boto: 2.46.1
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementMissing-datanp.nan, pd.NaT, pd.NA, dropna, isnull, interpolateNeeds DiscussionRequires discussion from core team before further actionReshapingConcat, Merge/Join, Stack/Unstack, Explode

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions