Skip to content

Commit a9c9203

Browse files
jorisvandenbosscheMeeseeksDev[bot]
authored and
MeeseeksDev[bot]
committed
Backport PR pandas-dev#27818: COMPAT: restore shape for 'invalid' Index with nd array
1 parent b17a030 commit a9c9203

File tree

4 files changed

+28
-2
lines changed

4 files changed

+28
-2
lines changed

doc/source/whatsnew/v0.25.1.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ Plotting
111111
^^^^^^^^
112112

113113
- Added a pandas_plotting_backends entrypoint group for registering plot backends. See :ref:`extending.plotting-backends` for more (:issue:`26747`).
114-
-
114+
- Fix compatibility issue with matplotlib when passing a pandas ``Index`` to a plot call (:issue:`27775`).
115115
-
116116

117117
Groupby/resample/rolling

pandas/core/indexes/base.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -5648,7 +5648,10 @@ def shape(self):
56485648
"""
56495649
Return a tuple of the shape of the underlying data.
56505650
"""
5651-
return (len(self),)
5651+
# not using "(len(self), )" to return "correct" shape if the values
5652+
# consists of a >1 D array (see GH-27775)
5653+
# overridden in MultiIndex.shape to avoid materializing the values
5654+
return self._values.shape
56525655

56535656

56545657
Index._add_numeric_methods_disabled()

pandas/core/indexes/multi.py

+9
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,15 @@ def _values(self):
616616
# We override here, since our parent uses _data, which we dont' use.
617617
return self.values
618618

619+
@property
620+
def shape(self):
621+
"""
622+
Return a tuple of the shape of the underlying data.
623+
"""
624+
# overriding the base Index.shape definition to avoid materializing
625+
# the values (GH-27384, GH-27775)
626+
return (len(self),)
627+
619628
@property
620629
def array(self):
621630
"""

pandas/tests/indexes/test_base.py

+14
Original file line numberDiff line numberDiff line change
@@ -2805,3 +2805,17 @@ def test_deprecated_fastpath():
28052805

28062806
expected = pd.CategoricalIndex(["a", "b", "c"], name="test")
28072807
tm.assert_index_equal(idx, expected)
2808+
2809+
2810+
def test_shape_of_invalid_index():
2811+
# Currently, it is possible to create "invalid" index objects backed by
2812+
# a multi-dimensional array (see https://github.com/pandas-dev/pandas/issues/27125
2813+
# about this). However, as long as this is not solved in general,this test ensures
2814+
# that the returned shape is consistent with this underlying array for
2815+
# compat with matplotlib (see https://github.com/pandas-dev/pandas/issues/27775)
2816+
a = np.arange(8).reshape(2, 2, 2)
2817+
idx = pd.Index(a)
2818+
assert idx.shape == a.shape
2819+
2820+
idx = pd.Index([0, 1, 2, 3])
2821+
assert idx[:, None].shape == (4, 1)

0 commit comments

Comments
 (0)