8000 Backport PR #18374: FIX: make _reshape_2D accept pandas df with strin… · matplotlib/matplotlib@e7bbfb0 · GitHub
[go: up one dir, main page]

Skip to content

Commit e7bbfb0

Browse files
dopplershiftmeeseeksmachine
authored andcommitted
Backport PR #18374: FIX: make _reshape_2D accept pandas df with string indices
1 parent f4f8448 commit e7bbfb0

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
@@ -1345,6 +1345,17 @@ def _reshape_2D(X, name):
13451345
13461346
*name* is used to generate the error message for invalid inputs.
13471347
"""
1348+
1349+
# unpack if we have a values or to_numpy method.
1350+
try:
1351+
X = X.to_numpy()
1352+
except AttributeError:
1353+
try:
1354+
if isinstance(X.values, np.ndarray):
1355+
X = X.values
1356+
except AttributeError:
1357+
pass
1358+
13481359
# Iterate over columns for ndarrays.
13491360
if isinstance(X, np.ndarray):
13501361
X = X.T

lib/matplotlib/tests/test_cbook.py

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

554554

555+
def test_reshape2d_pandas(pd):
556+
# seperate to allow the rest of the tests to run if no pandas...
557+
X = np.arange(30).reshape(10, 3)
558+
x = pd.DataFrame(X, columns=["a", "b", "c"])
559+
Xnew = cbook._reshape_2D(x, 'x')
560+
# Need to check each row because _reshape_2D returns a list of arrays:
561+
for x, xnew in zip(X.T, Xnew):
562+
np.testing.assert_array_equal(x, xnew)
563+
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+
555572
def test_contiguous_regions():
556573
a, b, c = 3, 4, 5
557574
# Starts and ends with True

0 commit comments

Comments
 (0)
0