Pandas: convert dtype 'object' to int

后端 未结 8 1938
南旧
南旧 2020-11-29 02:02

I\'ve read an SQL query into Pandas and the values are coming in as dtype \'object\', although they are strings, dates and integers. I am able to convert the date \'object\'

相关标签:
8条回答
  • 2020-11-29 02:33

    Follow these steps:

    1.clean your file -> open your datafile in csv format and see that there is "?" in place of empty places and delete all of them.

    2.drop the rows containing missing values e.g.:

    df.dropna(subset=["normalized-losses"], axis = 0 , inplace= True)
    

    3.use astype now for conversion

    df["normalized-losses"]=df["normalized-losses"].astype(int)
    

    Note: If still finding erros in your program then again inspect your csv file, open it in excel to find whether is there an "?" in your required column, then delete it and save file and go back and run your program.

    comment success! if it works. :)

    0 讨论(0)
  • 2020-11-29 02:36

    Documenting the answer that worked for me based on the comment by @piRSquared.

    I needed to convert to a string first, then an integer.

    >>> df['purchase'].astype(str).astype(int)
    
    0 讨论(0)
提交回复
热议问题