Skip to content

BUG: get_dummies not returning SparseDataFrame #10535

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
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 4 additions & 8 deletions doc/source/whatsnew/v0.17.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -377,16 +377,12 @@ Bug Fixes
- Bug in ``Series.plot(kind='hist')`` Y Label not informative (:issue:`10485`)










- Bug in operator equal on Index not being consistent with Series (:issue:`9947`)

- Reading "famafrench" data via ``DataReader`` results in HTTP 404 error because of the website url is changed (:issue:`10591`).

- Bug in `read_msgpack` where DataFrame to decode has duplicate column names (:issue:`9618`)


- Bug in `get_dummies` with `sparse=True` not returning SparseDataFrame (:issue:`10531`)

13 changes: 9 additions & 4 deletions pandas/core/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -957,13 +957,15 @@ def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False,
If `columns` is None then all the columns with
`object` or `category` dtype will be converted.
sparse : bool, default False
Whether the returned DataFrame should be sparse or not.
Whether the dummy columns should be sparse or not. Returns
SparseDataFrame if `data` is a Series or if all columns are included.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is confusing, I think we should just always return a SparseDataFrame.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about the case when some of the blocks are dense ? e.g.

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a':['A','B','C'],'b':['D','E','D']})

In [3]: pd.get_dummies(df, sparse=True, columns='b')
Out[3]: 
   a  b_D  b_E
0  A    1    0
1  B    0    1
2  C    1    0

Here a is still dense. Is a df where some blocks are dense and some sparse more accurately called a DataFrame or a SparseDataFrame?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Otherwise returns a DataFrame with some SparseBlocks.

.. versionadded:: 0.16.1

Returns
-------
dummies : DataFrame
dummies : DataFrame or SparseDataFrame

Examples
--------
Expand Down Expand Up @@ -1042,8 +1044,11 @@ def check_len(item, name):
elif isinstance(prefix_sep, dict):
prefix_sep = [prefix_sep[col] for col in columns_to_encode]

result = data.drop(columns_to_encode, axis=1)
with_dummies = [result]
if set(columns_to_encode) == set(data.columns):
with_dummies = []
else:
with_dummies = [data.drop(columns_to_encode, axis=1)]

for (col, pre, sep) in zip(columns_to_encode, prefix, prefix_sep):

dummy = _get_dummies_1d(data[col], prefix=pre, prefix_sep=sep,
Expand Down
28 changes: 28 additions & 0 deletions pandas/tests/test_reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import nose

from pandas import DataFrame, Series
from pandas.core.sparse import SparseDataFrame
import pandas as pd

from numpy import nan
Expand Down Expand Up @@ -171,6 +172,33 @@ def test_basic(self):
expected.index = list('ABC')
assert_frame_equal(get_dummies(s_series_index, sparse=self.sparse), expected)

def test_basic_types(self):
# GH 10531
s_list = list('abc')
s_series = Series(s_list)
s_df = DataFrame({'a': [0, 1, 0, 1, 2],
'b': ['A', 'A', 'B', 'C', 'C'],
'c': [2, 3, 3, 3, 2]})

if not self.sparse:
exp_df_type = DataFrame
exp_blk_type = pd.core.internals.FloatBlock
else:
exp_df_type = SparseDataFrame
exp_blk_type = pd.core.internals.SparseBlock

self.assertEqual(type(get_dummies(s_list, sparse=self.sparse)), exp_df_type)
self.assertEqual(type(get_dummies(s_series, sparse=self.sparse)), exp_df_type)

r = get_dummies(s_df, sparse=self.sparse, columns=s_df.columns)
self.assertEqual(type(r), exp_df_type)

r = get_dummies(s_df, sparse=self.sparse, columns=['a'])
self.assertEqual(type(r[['a_0']]._data.blocks[0]), exp_blk_type)
self.assertEqual(type(r[['a_1']]._data.blocks[0]), exp_blk_type)
self.assertEqual(type(r[['a_2']]._data.blocks[0]), exp_blk_type)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jreback How about now?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok looks reasonable

ping when green

FYI - don't take lines out of the what's new I put them there on purpose - helps avoid merge conflicts (in fact u have one now because of that)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jreback OK , green now.
Sorry about the whatsnew newlines (though I don't think there's a merge conflict?) So, where is a good place to insert whatsnew notes? Somewhere between two newlines?


def test_just_na(self):
just_na_list = [np.nan]
just_na_series = Series(just_na_list)
Expand Down