NumPy or Pandas: Keeping array type as integer while having a NaN value

前端 未结 8 1099
粉色の甜心
粉色の甜心 2020-11-22 06:05

Is there a preferred way to keep the data type of a numpy array fixed as int (or int64 or whatever), while still having an element ins

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 06:24

    Just wanted to add that in case you are trying to convert a float (1.143) vector to integer (1) that has NA converting to the new 'Int64' dtype will give you an error. In order to solve this you have to round the numbers and then do ".astype('Int64')"

    s1 = pd.Series([1.434, 2.343, np.nan])
    #without round() the next line returns an error 
    s1.astype('Int64')
    #cannot safely cast non-equivalent float64 to int64
    ##with round() it works
    s1.round().astype('Int64')
    0      1
    1      2
    2    NaN
    dtype: Int64
    

    My use case is that I have a float series that I want to round to int, but when you do .round() a '*.0' at the end of the number remains, so you can drop that 0 from the end by converting to int.

提交回复
热议问题