Convert float64 column to int64 in Pandas

前端 未结 4 1018
栀梦
栀梦 2020-12-23 21:14

I tried to convert a column from data type float64 to int64 using:

df[\'column name\'].astype(int64)

but got an e

4条回答
  •  粉色の甜心
    2020-12-23 22:08

    This seems to be a little buggy in Pandas 0.23.4?

    If there are np.nan values then this will throw an error as expected:

    df['col'] = df['col'].astype(np.int64)
    

    But doesn't change any values from float to int as I would expect if "ignore" is used:

    df['col'] = df['col'].astype(np.int64,errors='ignore') 
    

    It worked if I first converted np.nan:

    df['col'] = df['col'].fillna(0).astype(np.int64)
    df['col'] = df['col'].astype(np.int64)
    

    Now I can't figure out how to get null values back in place of the zeroes since this will convert everything back to float again:

    df['col']  = df['col'].replace(0,np.nan)
    

提交回复
热议问题