Skip to content

Commit d3eaffd

Browse files
authored
Merge pull request #18374 from jklymak/fix-reshape-pandas
FIX: make _reshape_2D accept pandas df with string indices
2 parents d9214de + cf9bb88 commit d3eaffd

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

lib/matplotlib/cbook/__init__.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1355,6 +1355,17 @@ def _reshape_2D(X, name):
13551355
13561356
*name* is used to generate the error message for invalid inputs.
13571357
"""
1358+
1359+
# unpack if we have a values or to_numpy method.
1360+
try:
1361+
X = X.to_numpy()
1362+
except AttributeError:
1363+
try:
1364+
if isinstance(X.values, np.ndarray):
1365+
X = X.values
1366+
except AttributeError:
1367+
pass
1368+
13581369
# Iterate over columns for ndarrays.
13591370
if isinstance(X, np.ndarray):
13601371
X = X.T

lib/matplotlib/tests/test_cbook.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,23 @@ def __getitem__(self, item):
559559
assert isinstance(xnew[0], np.ndarray)
560560

561561

562+
def test_reshape2d_pandas(pd):
563+
# seperate to allow the rest of the tests to run if no pandas...
564+
X = np.arange(30).reshape(10, 3)
565+
x = pd.DataFrame(X, columns=["a", "b", "c"])
566+
Xnew = cbook._reshape_2D(x, 'x')
567+
# Need to check each row because _reshape_2D returns a list of arrays:
568+
for x, xnew in zip(X.T, Xnew):
569+
np.testing.assert_array_equal(x, xnew)
570+
571+
X = np.arange(30).reshape(10, 3)
572+
x = pd.DataFrame(X, columns=["a", "b", "c"])
573+
Xnew = cbook._reshape_2D(x, 'x')
574+
# Need to check each row because _reshape_2D returns a list of arrays:
575+
for x, xnew in zip(X.T, Xnew):
576+
np.testing.assert_array_equal(x, xnew)
577+
578+
562579
def test_contiguous_regions():
563580
a, b, c = 3, 4, 5
564581
# Starts and ends with True

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy