Skip to content

Commit ffbfdb7

Browse files
committed
cbook.is_sequence_of_strings knows string objects
**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.
1 parent 5555f54 commit ffbfdb7

File tree

3 files changed

+41
-2
lines changed

3 files changed

+41
-2
lines changed

doc/users/whats_new/cbook.rst

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
cbook.is_sequence_of_strings recognizes string objects
2+
``````````````````````````````````````````````````````
3+
4+
This is primarily how pandas stores a sequence of strings.
5+
6+
import pandas as pd
7+
import matplotlib.cbook as cbook
8+
9+
a = np.array(['a', 'b', 'c'])
10+
print(cbook.is_sequence_of_strings(a)) # True
11+
12+
a = np.array(['a', 'b', 'c'], dtype=object)
13+
print(cbook.is_sequence_of_strings(a)) # True
14+
15+
s = pd.Series(['a', 'b', 'c'])
16+
print(cbook.is_sequence_of_strings(s)) # True
17+
18+
Previously, the last two prints returned false.

lib/matplotlib/cbook.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -783,8 +783,12 @@ def is_sequence_of_strings(obj):
783783
"""
784784
if not iterable(obj):
785785
return False
786-
if is_string_like(obj):
787-
return False
786+
if is_string_like(obj) and not isinstance(obj, np.ndarray):
787+
try:
788+
obj = obj.values
789+
except AttributeError:
790+
# not pandas
791+
return False
788792
for o in obj:
789793
if not is_string_like(o):
790794
return False

lib/matplotlib/tests/test_cbook.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,23 @@ def test_is_string_like():
2626
assert cbook.is_string_like("hello world")
2727
assert_equal(cbook.is_string_like(10), False)
2828

29+
y = ['a', 'b', 'c']
30+
assert_equal(cbook.is_string_like(y), False)
31+
32+
y = np.array(y)
33+
assert_equal(cbook.is_string_like(y), False)
34+
35+
y = np.array(y, dtype=object)
36+
assert cbook.is_string_like(y)
37+
38+
39+
def test_is_sequence_of_strings():
40+
y = ['a', 'b', 'c']
41+
assert cbook.is_sequence_of_strings(y)
42+
43+
y = np.array(y, dtype=object)
44+
assert cbook.is_sequence_of_strings(y)
45+
2946

3047
def test_restrict_dict():
3148
d = {'foo': 'bar', 1: 2}

0 commit comments

Comments
 (0)