Skip to content

Commit 760f63b

Browse files
committed
Merge pull request #7464 from cpcloud/float64index-bad-construction
BUG: astype(float) in Index does the wrong thing
2 parents 8d209de + dcb707f commit 760f63b

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

doc/source/v0.14.1.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,8 @@ Bug Fixes
229229

230230

231231

232-
232+
- Bug in ``Index.astype(float)`` where it would return an ``object`` dtype
233+
``Index`` (:issue:`7464`).
233234

234235

235236

pandas/core/index.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,8 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False,
140140

141141
if issubclass(data.dtype.type, np.integer):
142142
return Int64Index(data, copy=copy, dtype=dtype, name=name)
143+
if issubclass(data.dtype.type, np.floating):
144+
return Float64Index(data, copy=copy, dtype=dtype, name=name)
143145

144146
subarr = com._asarray_tuplesafe(data, dtype=object)
145147

@@ -1986,7 +1988,8 @@ def inferred_type(self):
19861988
def astype(self, dtype):
19871989
if np.dtype(dtype) not in (np.object, np.float64):
19881990
raise TypeError('Setting %s dtype to anything other than '
1989-
'float64 or object is not supported' % self.__class__)
1991+
'float64 or object is not supported' %
1992+
self.__class__)
19901993
return Index(self.values, name=self.name, dtype=dtype)
19911994

19921995
def _convert_scalar_indexer(self, key, typ=None):
@@ -2020,7 +2023,7 @@ def get_value(self, series, key):
20202023
k = _values_from_object(key)
20212024
loc = self.get_loc(k)
20222025
new_values = series.values[loc]
2023-
if np.isscalar(new_values):
2026+
if np.isscalar(new_values) or new_values is None:
20242027
return new_values
20252028

20262029
new_index = self[loc]

pandas/tests/test_index.py

+8
Original file line numberDiff line numberDiff line change
@@ -905,6 +905,7 @@ def test_nan_first_take_datetime(self):
905905
exp = Index([idx[-1], idx[0], idx[1]])
906906
tm.assert_index_equal(res, exp)
907907

908+
908909
class TestFloat64Index(tm.TestCase):
909910
_multiprocess_can_split_ = True
910911

@@ -1041,6 +1042,13 @@ def test_nan_multiple_containment(self):
10411042
np.testing.assert_array_equal(i.isin([np.nan]),
10421043
np.array([False, False]))
10431044

1045+
def test_astype_from_object(self):
1046+
index = Index([1.0, np.nan, 0.2], dtype='object')
1047+
result = index.astype(float)
1048+
expected = Float64Index([1.0, np.nan, 0.2])
1049+
tm.assert_equal(result.dtype, expected.dtype)
1050+
tm.assert_index_equal(result, expected)
1051+
10441052

10451053
class TestInt64Index(tm.TestCase):
10461054
_multiprocess_can_split_ = True

0 commit comments

Comments
 (0)