Skip to content

Commit

Permalink
Merge pull request #4358 from has2k1/sequence-string
Browse files Browse the repository at this point in the history
FIX : cbook.is_sequence_of_strings behave better on array/pd.series of strings
  • Loading branch information
tacaswell committed Apr 30, 2015
2 parents 2d91ca6 + ffbfdb7 commit b091e26
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
18 changes: 18 additions & 0 deletions doc/users/whats_new/cbook.rst
@@ -0,0 +1,18 @@
cbook.is_sequence_of_strings recognizes string objects
``````````````````````````````````````````````````````

This is primarily how pandas stores a sequence of strings.

import pandas as pd
import matplotlib.cbook as cbook

a = np.array(['a', 'b', 'c'])
print(cbook.is_sequence_of_strings(a)) # True

a = np.array(['a', 'b', 'c'], dtype=object)
print(cbook.is_sequence_of_strings(a)) # True

s = pd.Series(['a', 'b', 'c'])
print(cbook.is_sequence_of_strings(s)) # True

Previously, the last two prints returned false.
8 changes: 6 additions & 2 deletions lib/matplotlib/cbook.py
Expand Up @@ -783,8 +783,12 @@ def is_sequence_of_strings(obj):
"""
if not iterable(obj):
return False
if is_string_like(obj):
return False
if is_string_like(obj) and not isinstance(obj, np.ndarray):
try:
obj = obj.values
except AttributeError:
# not pandas
return False
for o in obj:
if not is_string_like(o):
return False
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 b091e26

Please sign in to comment.