From e7bbfb058344afbac507837808da277a4c41092e Mon Sep 17 00:00:00 2001 From: Ryan May Date: Sun, 30 Aug 2020 16:05:06 -0600 Subject: [PATCH] Backport PR #18374: FIX: make _reshape_2D accept pandas df with string indices --- lib/matplotlib/cbook/__init__.py | 11 +++++++++++ lib/matplotlib/tests/test_cbook.py | 17 +++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/lib/matplotlib/cbook/__init__.py b/lib/matplotlib/cbook/__init__.py index 836de0c4a408..453a5a995380 100644 --- a/lib/matplotlib/cbook/__init__.py +++ b/lib/matplotlib/cbook/__init__.py @@ -1345,6 +1345,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 9c00f892e687..67a66ea2a8bf 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -552,6 +552,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