Skip to content

Commit

Permalink
cbook.is_sequence_of_strings knows string objects
Browse files Browse the repository at this point in the history
**Issue**
`cbook.is_sequence_of_strings` cannot tell of a pandas series
is contains strings. Pandas series are numpy arrays of type
`object`.

**Problem**
`cbook.is_sequence_of_strings` uses `cbook.is_string_like` to dismiss
strings as not sequences of strings. However, numpy string arrays
of `dtype=object` are string-like since they support string
concatenation.

**Solution**
Do not dismiss an `ndarray` if it appears string-like, go ahead and
peak inside.
  • Loading branch information
has2k1 committed Apr 20, 2015
1 parent 62cce14 commit fdb954d
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
16 changes: 16 additions & 0 deletions doc/users/whats_new/cbook.rst
@@ -0,0 +1,16 @@
cbook.is_sequence_of_strings recognizes string objects
``````````````````````````````````````````````````````

This is primarily how pandas stores a sequence of strings.

>>> import pandas as pd
>>> import matplotilb.cbook as cbook
>>> a = np.array(['a', 'b', 'c'])
>>> cbook.sequence_of_strings(a)
False
>>> a = np.array(['a', 'b', 'c'], dtype=object)
>>> cbook.sequence_of_strings(a)
True
>>> s = pd.Series(['a', 'b', 'c])]
>>> cbook.sequence_of_strings(s)
True
2 changes: 1 addition & 1 deletion lib/matplotlib/cbook.py
Expand Up @@ -783,7 +783,7 @@ def is_sequence_of_strings(obj):
"""
if not iterable(obj):
return False
if is_string_like(obj):
if is_string_like(obj) and not isinstance(obj, np.ndarray):
return False
for o in obj:
if not is_string_like(o):
Expand Down
17 changes: 17 additions & 0 deletions lib/matplotlib/tests/test_cbook.py
Expand Up @@ -26,6 +26,23 @@ def test_is_string_like():
assert cbook.is_string_like("hello world")
assert_equal(cbook.is_string_like(10), False)

y = ['a', 'b', 'c']
assert_equal(cbook.is_string_like(y), False)

y = np.array(y)
assert_equal(cbook.is_string_like(y), False)

y = np.array(y, dtype=object)
assert cbook.is_string_like(y)


def test_is_sequence_of_strings():
y = ['a', 'b', 'c']
assert cbook.is_sequence_of_strings(y)

y = np.array(y, dtype=object)
assert cbook.is_sequence_of_strings(y)


def test_restrict_dict():
d = {'foo': 'bar', 1: 2}
Expand Down

0 comments on commit fdb954d

Please sign in to comment.