Skip to content

Commit d7dcdf3

Browse files
COMPAT: restore shape for 'invalid' Index with nd array (#27818)
1 parent 8b6942f commit d7dcdf3

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
@@ -112,7 +112,7 @@ Plotting
112112
^^^^^^^^
113113

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

118118
Groupby/resample/rolling

pandas/core/indexes/base.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -5604,7 +5604,10 @@ def shape(self):
56045604
"""
56055605
Return a tuple of the shape of the underlying data.
56065606
"""
5607-
return (len(self),)
5607+
# not using "(len(self), )" to return "correct" shape if the values
5608+
# consists of a >1 D array (see GH-27775)
5609+
# overridden in MultiIndex.shape to avoid materializing the values
5610+
return self._values.shape
56085611

56095612

56105613
Index._add_numeric_methods_disabled()

pandas/core/indexes/multi.py

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

625+
@property
626+
def shape(self):
627+
"""
628+
Return a tuple of the shape of the underlying data.
629+
"""
630+
# overriding the base Index.shape definition to avoid materializing
631+
# the values (GH-27384, GH-27775)
632+
return (len(self),)
633+
625634
@property
626635
def array(self):
627636
"""

pandas/tests/indexes/test_base.py

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

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

0 commit comments

Comments
 (0)