Skip to content

Fix item check for pandas Series #12973

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

Closed
Closed
Show file tree
Hide file tree
Changes from all 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: 6 additions & 3 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,12 @@ def _has_item(data, name):
availability) and with numpy.arrays.
"""
try:
return data.dtype.names is not None and name in data.dtype.names
except AttributeError: # not a numpy array
return name in data
if not type(data).__name__ == 'Series':
# numpy array
return data.dtype.names is not None and name in data.dtype.names
except AttributeError:
pass
return name in data


def _plot_args_replacer(args, data):
Expand Down
22 changes: 22 additions & 0 deletions lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,35 @@
assert_allclose, assert_array_equal, assert_array_almost_equal)
from matplotlib.cbook import (
IgnoredKeywordWarning, MatplotlibDeprecationWarning)
from matplotlib.axes._axes import _has_item

# Note: Some test cases are run twice: once normally and once with labeled data
# These two must be defined in the same test function or need to have
# different baseline images to prevent race conditions when pytest runs
# the tests with multiple threads.


def test_has_item():
d = {'a': 1, 'b': 2}
assert _has_item(d, 'a')
assert not _has_item(d, 'c')
d = np.array([(1, 11), (2, 22)], dtype=[('a', float), ('b', float)])
assert _has_item(d, 'a')
assert not _has_item(d, 'c')
d = np.array([1, 2])
assert not _has_item(d, 'a')


def test_has_item_pandas(pd):
s = pd.Series([1, 2], index=['a', 'b'])
assert _has_item(s, 'a')
assert not _has_item(s, 'c')
df = pd.DataFrame([[1, 2], [3, 4]], index=['A', 'B'], columns=['a', 'b'])
assert _has_item(df, 'a')
assert not _has_item(df, 'A')
assert not _has_item(df, 'c')


def test_get_labels():
fig, ax = plt.subplots()
ax.set_xlabel('x label')
Expand Down