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

make Table.to_dataframe create real sparse frames #809

Merged
merged 4 commits into from
Mar 7, 2019
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
9 changes: 5 additions & 4 deletions biom/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@
from copy import deepcopy
from datetime import datetime
from json import dumps
from functools import reduce
from functools import reduce, partial
from operator import itemgetter
from future.builtins import zip
from future.utils import viewitems
Expand Down Expand Up @@ -4045,9 +4045,10 @@ def to_dataframe(self, dense=False):
mat = self.matrix_data.toarray()
constructor = pd.DataFrame
else:
mat = [pd.SparseSeries(r.toarray().squeeze())
for r in self.matrix_data.tocsr()]
constructor = pd.SparseDataFrame
mat = self.matrix_data
constructor = partial(pd.SparseDataFrame,
default_fill_value=0,
copy=True)

return constructor(mat, index=index, columns=columns)

Expand Down
9 changes: 8 additions & 1 deletion biom/tests/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -1475,10 +1475,17 @@ def test_add_group_metadata_w_existing_metadata(self):
def test_to_dataframe(self):
exp = pd.SparseDataFrame(np.array([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]),
index=['O1', 'O2'],
columns=['S1', 'S2', 'S3'])
columns=['S1', 'S2', 'S3'],
default_fill_value=0.0)
obs = example_table.to_dataframe()
pdt.assert_frame_equal(obs, exp)

def test_to_dataframe_is_sparse(self):
df = example_table.to_dataframe()
density = (example_table.matrix_data.getnnz() /
np.prod(example_table.shape))
assert np.allclose(df.density, density)

def test_to_dataframe_dense(self):
exp = pd.DataFrame(np.array([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]),
index=['O1', 'O2'],
Expand Down