From f8529060e01a033d16feed4064797030aa9ffd3f Mon Sep 17 00:00:00 2001 From: Stephan Hoyer Date: Wed, 28 May 2014 16:44:59 -0700 Subject: [PATCH] ENH: check for __array__ instead of ndarray subclasses when creating an Index This allows custom ndarray-like objects which aren't actual ndarrays to be smoothly cast to a pandas.Index: https://github.com/pydata/pandas/issues/5460#issuecomment-44474502 --- pandas/core/common.py | 3 ++- pandas/tests/test_index.py | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/pandas/core/common.py b/pandas/core/common.py index 00fa970c0f77a..afa376a14d4da 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -2038,7 +2038,8 @@ def intersection(*seqs): def _asarray_tuplesafe(values, dtype=None): from pandas.core.index import Index - if not isinstance(values, (list, tuple, np.ndarray)): + if not (isinstance(values, (list, tuple)) + or hasattr(values, '__array__')): values = list(values) elif isinstance(values, Index): return values.values diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index 105fdbb32ab22..2d3effc251e0b 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -173,6 +173,18 @@ def test_constructor_from_series(self): result = pd.infer_freq(df['date']) self.assertEqual(result,'MS') + def test_constructor_ndarray_like(self): + # GH 5460#issuecomment-44474502 + # it should be possible to convert any object that satisfies the numpy + # ndarray interface directly into an Index + class ArrayLike(object): + def __array__(self, dtype=None): + return np.arange(5) + + expected = pd.Index(np.arange(5)) + result = pd.Index(ArrayLike()) + self.assertTrue(result.equals(expected)) + def test_index_ctor_infer_periodindex(self): from pandas import period_range, PeriodIndex xp = period_range('2012-1-1', freq='M', periods=3)