diff --git a/lib/matplotlib/cbook/__init__.py b/lib/matplotlib/cbook/__init__.py index f7dfa4c02b50..9281faff4f5d 100644 --- a/lib/matplotlib/cbook/__init__.py +++ b/lib/matplotlib/cbook/__init__.py @@ -1355,6 +1355,17 @@ def _reshape_2D(X, name): *name* is used to generate the error message for invalid inputs. """ + + # unpack if we have a values or to_numpy method. + try: + X = X.to_numpy() + except AttributeError: + try: + if isinstance(X.values, np.ndarray): + X = X.values + except AttributeError: + pass + # Iterate over columns for ndarrays. if isinstance(X, np.ndarray): X = X.T diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 73560195b7b9..de99701d7757 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -559,6 +559,23 @@ def __getitem__(self, item): assert isinstance(xnew[0], np.ndarray) +def test_reshape2d_pandas(pd): + # seperate to allow the rest of the tests to run if no pandas... + X = np.arange(30).reshape(10, 3) + x = pd.DataFrame(X, columns=["a", "b", "c"]) + Xnew = cbook._reshape_2D(x, 'x') + # Need to check each row because _reshape_2D returns a list of arrays: + for x, xnew in zip(X.T, Xnew): + np.testing.assert_array_equal(x, xnew) + + X = np.arange(30).reshape(10, 3) + x = pd.DataFrame(X, columns=["a", "b", "c"]) + Xnew = cbook._reshape_2D(x, 'x') + # Need to check each row because _reshape_2D returns a list of arrays: + for x, xnew in zip(X.T, Xnew): + np.testing.assert_array_equal(x, xnew) + + def test_contiguous_regions(): a, b, c = 3, 4, 5 # Starts and ends with True