Convert Pandas column containing NaNs to dtype `int`

后端 未结 17 2420
终归单人心
终归单人心 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:08

    My use case is munging data prior to loading into a DB table:

    df[col] = df[col].fillna(-1)
    df[col] = df[col].astype(int)
    df[col] = df[col].astype(str)
    df[col] = df[col].replace('-1', np.nan)
    

    Remove NaNs, convert to int, convert to str and then reinsert NANs.

    It's not pretty but it gets the job done!

提交回复
热议问题