Convert Pandas column containing NaNs to dtype `int`

后端 未结 17 2365
终归单人心
终归单人心 2020-11-22 11:18

I read data from a .csv file to a Pandas dataframe as below. For one of the columns, namely id, I want to specify the column type as int. The probl

17条回答
  •  情深已故
    2020-11-22 12:05

    In version 0.24.+ pandas has gained the ability to hold integer dtypes with missing values.

    Nullable Integer Data Type.

    Pandas can represent integer data with possibly missing values using arrays.IntegerArray. This is an extension types implemented within pandas. It is not the default dtype for integers, and will not be inferred; you must explicitly pass the dtype into array() or Series:

    arr = pd.array([1, 2, np.nan], dtype=pd.Int64Dtype())
    pd.Series(arr)
    
    0      1
    1      2
    2    NaN
    dtype: Int64
    

    For convert column to nullable integers use:

    df['myCol'] = df['myCol'].astype('Int64')
    

提交回复
热议问题