Python: prevent values ​​in Pandas rounding to integer

I tried to set some values ​​in the Series, but it will be automatically rounded to an integer, what should I do to prevent this?

from __future__ import division import pandas as pd In [100]: series = pd.Series(range(20)) In [101]: series[10] Out[101]: 10 In [102]: series[10] = 0.05 In [103]: series[10] Out[103]: 0 In [104]: series[10] = 2.5 In [105]: series[10] Out[105]: 2 In [106]: series[10] = float(2.5) In [107]: series[10] Out[107]: 2 In [108]: float(2/3) Out[108]: 0.6666666666666666 In [109]: series[10] = float(2/3) In [110]: series[10] Out[110]: 0 
+5
source share
1 answer

series automatically created with the int64 data int64 (since range(20) contains only integers). When you try to set the value of this series to float, the values ​​are truncated to an integer because Pandas will not automatically advertise the Series data type. *

The easiest way is to create a series with the required data type:

 series = pd.Series(range(20), dtype=float) 

Or you can overlay an integer series after creating it:

 series = series.astype(float) 

Then you can set the float values ​​in Series.


* This is somewhat similar to the behavior of NumPy with arrays. However, unlike NumPy, Pandas will promote the Series data type from integer to floating type if you try to set the nan value:

 series[10] = np.nan # series is promoted to float64 type 

Pandas will also push the series to the object type if you try to set a string value:

 series[5] = 'some string' # series is promoted to object type 
+5
source

All Articles