Skip to content

Commit f9bcce7

Browse files
committed
Merge pull request #7270 from shoyer/use-__array__
ENH: check for __array__ instead of ndarray subclasses when creating an Index
2 parents 0f0fb94 + f852906 commit f9bcce7

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

pandas/core/common.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -2038,7 +2038,8 @@ def intersection(*seqs):
20382038
def _asarray_tuplesafe(values, dtype=None):
20392039
from pandas.core.index import Index
20402040

2041-
if not isinstance(values, (list, tuple, np.ndarray)):
2041+
if not (isinstance(values, (list, tuple))
2042+
or hasattr(values, '__array__')):
20422043
values = list(values)
20432044
elif isinstance(values, Index):
20442045
return values.values

pandas/tests/test_index.py

+12
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,18 @@ def test_constructor_from_series(self):
173173
result = pd.infer_freq(df['date'])
174174
self.assertEqual(result,'MS')
175175

176+
def test_constructor_ndarray_like(self):
177+
# GH 5460#issuecomment-44474502
178+
# it should be possible to convert any object that satisfies the numpy
179+
# ndarray interface directly into an Index
180+
class ArrayLike(object):
181+
def __array__(self, dtype=None):
182+
return np.arange(5)
183+
184+
expected = pd.Index(np.arange(5))
185+
result = pd.Index(ArrayLike())
186+
self.assertTrue(result.equals(expected))
187+
176188
def test_index_ctor_infer_periodindex(self):
177189
from pandas import period_range, PeriodIndex
178190
xp = period_range('2012-1-1', freq='M', periods=3)

0 commit comments

Comments
 (0)