@@ -203,6 +203,9 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None,
203
203
if inferred == 'integer' :
204
204
data = np .array (data , copy = copy , dtype = dtype )
205
205
elif inferred in ['floating' , 'mixed-integer-float' ]:
206
+ if isnull (data ).any ():
207
+ raise ValueError ('cannot convert float '
208
+ 'NaN to integer' )
206
209
207
210
# If we are actually all equal to integers,
208
211
# then coerce to integer.
@@ -230,8 +233,10 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None,
230
233
else :
231
234
data = np .array (data , dtype = dtype , copy = copy )
232
235
233
- except (TypeError , ValueError ):
234
- pass
236
+ except (TypeError , ValueError ) as e :
237
+ msg = str (e )
238
+ if 'cannot convert float' in msg :
239
+ raise
235
240
236
241
# maybe coerce to a sub-class
237
242
from pandas .tseries .period import (PeriodIndex ,
@@ -585,7 +590,14 @@ def where(self, cond, other=None):
585
590
if other is None :
586
591
other = self ._na_value
587
592
values = np .where (cond , self .values , other )
588
- return self ._shallow_copy_with_infer (values , dtype = self .dtype )
593
+
594
+ dtype = self .dtype
595
+ if self ._is_numeric_dtype and np .any (isnull (values )):
596
+ # We can't coerce to the numeric dtype of "self" (unless
597
+ # it's float) if there are NaN values in our output.
598
+ dtype = None
599
+
600
+ return self ._shallow_copy_with_infer (values , dtype = dtype )
589
601
590
602
def ravel (self , order = 'C' ):
591
603
"""
@@ -689,7 +701,14 @@ def _coerce_scalar_to_index(self, item):
689
701
----------
690
702
item : scalar item to coerce
691
703
"""
692
- return Index ([item ], dtype = self .dtype , ** self ._get_attributes_dict ())
704
+ dtype = self .dtype
705
+
706
+ if self ._is_numeric_dtype and isnull (item ):
707
+ # We can't coerce to the numeric dtype of "self" (unless
708
+ # it's float) if there are NaN values in our output.
709
+ dtype = None
710
+
711
+ return Index ([item ], dtype = dtype , ** self ._get_attributes_dict ())
693
712
694
713
_index_shared_docs ['copy' ] = """
695
714
Make a copy of this object. Name and dtype sets those attributes on
0 commit comments