Skip to content

Commit

Permalink
implicit sequences as columns
Browse files Browse the repository at this point in the history
  • Loading branch information
papajohn committed Jul 20, 2015
1 parent 11b172c commit 30e8c93
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
19 changes: 15 additions & 4 deletions datascience.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ def __getitem__(self, label):
def __setitem__(self, label, values):
if not isinstance(values, np.ndarray):
# Coerce a single value to a sequence
if isinstance(values, str) or not isinstance(values, collections.abc.Sequence):
if not _is_non_string_iterable(values):
values = [values] * max(self.num_rows, 1)
values = np.array(values)
values = np.array(tuple(values))
if hasattr(self, '_num_rows') & self.num_rows > 0:
assert len(values) == self.num_rows, 'column length mismatch'
else:
Expand Down Expand Up @@ -689,15 +689,15 @@ def _fill_with_zeroes(order, rows, zero=None):
assert len(rows) > 0
index = dict(rows)
if zero is None:
array = np.array(list(index.values()))
array = np.array(tuple(index.values()))
if len(array.shape) == 1:
zero = array.dtype.type()
return np.array([index.get(k, zero) for k in order])


def _as_labels(column_label_or_labels):
"""Return a list of labels for a label or labels."""
if not isinstance(column_label_or_labels, collections.abc.Sequence):
if not _is_non_string_iterable(column_label_or_labels):
return [column_label_or_labels]
else:
return column_label_or_labels
Expand All @@ -718,3 +718,14 @@ def _collected_label(collect, label):
return label + ' ' + collect.__name__
else:
return label


def _is_non_string_iterable(value):
"""Whether a value is iterable."""
if isinstance(value, str):
return False
if hasattr(value, '__iter__'):
return True
if isinstance(value, collections.abc.Sequence):
return True
return False
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def run_tests(self):
setup(
name = 'datascience',
py_modules = ['datascience'],
version = '0.2.0',
version = '0.2.1',
install_requires = install_requires,
tests_require = test_requires,
cmdclass = {'test': PyTest},
Expand Down
11 changes: 11 additions & 0 deletions tests/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,17 @@ def test_tuples(t, u):
""")


def test_keys_and_values():
"""Tests that a table can be constructed from keys and values."""
d = {1: 2, 3: 4}
t = Table([d.keys(), d.values()], ['keys', 'values'])
assert_equal(t, """\
keys | values
1 | 2
3 | 4
""")


##########
# Modify #
##########
Expand Down

0 comments on commit 30e8c93

Please sign in to comment.