diff --git a/doc/source/v0.14.1.txt b/doc/source/v0.14.1.txt index be0b3bc543c39..61ffd5c89b568 100644 --- a/doc/source/v0.14.1.txt +++ b/doc/source/v0.14.1.txt @@ -229,7 +229,8 @@ Bug Fixes - +- Bug in ``Index.astype(float)`` where it would return an ``object`` dtype + ``Index`` (:issue:`7464`). diff --git a/pandas/core/index.py b/pandas/core/index.py index 2252ba666ca59..4f1c1d4f65a4c 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -140,6 +140,8 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False, if issubclass(data.dtype.type, np.integer): return Int64Index(data, copy=copy, dtype=dtype, name=name) + if issubclass(data.dtype.type, np.floating): + return Float64Index(data, copy=copy, dtype=dtype, name=name) subarr = com._asarray_tuplesafe(data, dtype=object) @@ -1986,7 +1988,8 @@ def inferred_type(self): def astype(self, dtype): if np.dtype(dtype) not in (np.object, np.float64): raise TypeError('Setting %s dtype to anything other than ' - 'float64 or object is not supported' % self.__class__) + 'float64 or object is not supported' % + self.__class__) return Index(self.values, name=self.name, dtype=dtype) def _convert_scalar_indexer(self, key, typ=None): @@ -2020,7 +2023,7 @@ def get_value(self, series, key): k = _values_from_object(key) loc = self.get_loc(k) new_values = series.values[loc] - if np.isscalar(new_values): + if np.isscalar(new_values) or new_values is None: return new_values new_index = self[loc] diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py index f2372f98b330b..0bef5678b6825 100644 --- a/pandas/tests/test_index.py +++ b/pandas/tests/test_index.py @@ -905,6 +905,7 @@ def test_nan_first_take_datetime(self): exp = Index([idx[-1], idx[0], idx[1]]) tm.assert_index_equal(res, exp) + class TestFloat64Index(tm.TestCase): _multiprocess_can_split_ = True @@ -1041,6 +1042,13 @@ def test_nan_multiple_containment(self): np.testing.assert_array_equal(i.isin([np.nan]), np.array([False, False])) + def test_astype_from_object(self): + index = Index([1.0, np.nan, 0.2], dtype='object') + result = index.astype(float) + expected = Float64Index([1.0, np.nan, 0.2]) + tm.assert_equal(result.dtype, expected.dtype) + tm.assert_index_equal(result, expected) + class TestInt64Index(tm.TestCase): _multiprocess_can_split_ = True