Skip to content
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

BUG: Fix make_sparse mask generation #17574

Merged
merged 12 commits into from
Sep 28, 2017
Merged
Show file tree
Hide file tree
Changes from 2 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: 11 additions & 1 deletion pandas/core/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from pandas.core.dtypes.common import (
_ensure_platform_int,
is_float, is_integer,
is_object_dtype,
is_integer_dtype,
is_bool_dtype,
is_list_like,
Expand Down Expand Up @@ -789,7 +790,16 @@ def make_sparse(arr, kind='block', fill_value=None):
if is_string_dtype(arr):
arr = arr.astype(object)

mask = arr != fill_value
if is_object_dtype(arr.dtype):
mask = []
for e in arr:
if type(e) is type(fill_value):
mask.append(e != fill_value)
else:
mask.append(True)
mask = np.array(mask)
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 very awkward

you can do this by starting with an array of True
the using .flat to set only the portion you need and do that with a list comprehension

else:
mask = arr != fill_value

length = len(arr)
if length != mask.size:
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/sparse/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ def test_constructor_object_dtype(self):
assert arr.dtype == np.object
assert arr.fill_value == 'A'

data = [False, 0, 100.0, 0.0]
Copy link
Contributor

Choose a reason for hiding this comment

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

add the issues number as a comment

arr = SparseArray(data, dtype=np.object, fill_value=False)
assert arr.dtype == np.object
assert arr.fill_value is False
assert (arr == np.array(data, dtype=np.object)).to_dense().all()

def test_constructor_spindex_dtype(self):
arr = SparseArray(data=[1, 2], sparse_index=IntIndex(4, [1, 2]))
tm.assert_sp_array_equal(arr, SparseArray([np.nan, 1, 2, np.nan]))
Expand Down