Skip to content
Merged
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
18 changes: 17 additions & 1 deletion sparsity/sparse_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ def _is_empty(data):
return True
return False


class SparseFrame(object):
"""
Simple sparse table based on scipy.sparse.csr_matrix
Expand All @@ -62,12 +63,27 @@ def __init__(self, data, index=None, columns=None, **kwargs):

if index is None:
self._index = _default_index(N)
elif len(index) != N and data.size:
if columns is not None:
implied_axis_1 = len(columns)
else:
implied_axis_1 = data.shape[1]
raise ValueError('Shape of passed values is {},'
'indices imply {}'
.format(data.shape, (len(index), implied_axis_1)))
else:
# assert len(index) == N
self._index = _ensure_index(index)

if columns is None:
self._columns = _default_index(K)
elif len(columns) != K and data.size:
if index is not None:
implied_axis_0 = len(index)
else:
implied_axis_0 = data.shape[0]
raise ValueError('Shape of passed values is {},'
'indices imply {}'
.format(data.shape, (implied_axis_0, len(columns))))
else:
# assert len(columns) == K
self._columns = _ensure_index(columns)
Expand Down
17 changes: 17 additions & 0 deletions sparsity/test/test_sparse_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ def test_empty_init():
sf = SparseFrame(np.array([]), index=[], columns=['A', 'B'])
assert sf.data.shape == (0, 2)

sf = SparseFrame(np.array([]), index=['A', 'B'], columns=[])
assert sf.data.shape == (2, 0)

def test_groupby(groupby_frame):
t = groupby_frame
Expand Down Expand Up @@ -915,3 +917,18 @@ def test_loc_duplicate_index():

assert len(sf.loc[:, 'U'].columns) == 2
assert np.all(sf.loc[:, 'U'].todense().values == np.identity(5)[:, :2])


def test_error_unaligned_indices():
data = np.identity(5)
with pytest.raises(ValueError) as e:
SparseFrame(data, index=np.arange(6))
assert '(5, 5)' in str(e) and '(6, 5)' in str(e)

with pytest.raises(ValueError) as e:
SparseFrame(data, columns=np.arange(6))
assert '(5, 5)' in str(e) and '(5, 6)' in str(e)

with pytest.raises(ValueError) as e:
SparseFrame(data, columns=np.arange(6), index=np.arange(6))
assert '(5, 5)' in str(e) and '(6, 6)' in str(e)