@@ -28,6 +28,7 @@ class Block(object):
2828 is_bool = False
2929 is_object = False
3030 _can_hold_na = False
31+ _downcast_dtype = None
3132
3233 def __init__ (self , values , items , ref_items , ndim = 2 ):
3334 if issubclass (values .dtype .type , basestring ):
@@ -205,7 +206,7 @@ def split_block_at(self, item):
205206 self .items [s :e ].copy (),
206207 self .ref_items )
207208
208- def fillna (self , value , inplace = False ):
209+ def fillna (self , value , inplace = False , downcast = None ):
209210 if not self ._can_hold_na :
210211 if inplace :
211212 return self
@@ -216,10 +217,32 @@ def fillna(self, value, inplace=False):
216217 mask = com .isnull (new_values )
217218 np .putmask (new_values , mask , value )
218219
219- if inplace :
220- return self
221- else :
222- return make_block (new_values , self .items , self .ref_items )
220+ block = make_block (new_values , self .items , self .ref_items )
221+ if downcast :
222+ block = block .downcast ()
223+ return block
224+
225+ def downcast (self , dtypes = None ):
226+ """ try to downcast each item to the dict of dtypes if present """
227+
228+ if dtypes is None :
229+ dtypes = dict ()
230+
231+ values = self .values
232+ blocks = []
233+ for i , item in enumerate (self .items ):
234+
235+ dtype = dtypes .get (item ,self ._downcast_dtype )
236+ if dtype is None :
237+ nv = _block_shape (values [i ])
238+ blocks .append (make_block (nv , [ item ], self .ref_items ))
239+ continue
240+
241+ nv = _possibly_downcast_to_dtype (values [i ], np .dtype (dtype ))
242+ nv = _block_shape (nv )
243+ blocks .append (make_block (nv , [ item ], self .ref_items ))
244+
245+ return blocks
223246
224247 def astype (self , dtype , copy = True , raise_on_error = True ):
225248 """
@@ -563,6 +586,7 @@ def _try_cast_result(self, result):
563586 return _possibly_downcast_to_dtype (result , self .dtype )
564587
565588class FloatBlock (NumericBlock ):
589+ _downcast_dtype = 'int64'
566590
567591 def _can_hold_element (self , element ):
568592 if isinstance (element , np .ndarray ):
@@ -974,6 +998,9 @@ def shift(self, *args, **kwargs):
974998 def fillna (self , * args , ** kwargs ):
975999 return self .apply ('fillna' , * args , ** kwargs )
9761000
1001+ def downcast (self , * args , ** kwargs ):
1002+ return self .apply ('downcast' , * args , ** kwargs )
1003+
9771004 def astype (self , * args , ** kwargs ):
9781005 return self .apply ('astype' , * args , ** kwargs )
9791006
0 commit comments