Pandas: convert dtype 'object' to int

后端 未结 8 2022
南旧
南旧 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:24

    In my case, I had a df with mixed data:

    df:
                         0   1   2    ...                  242                  243                  244
    0   2020-04-22T04:00:00Z   0   0  ...          3,094,409.5         13,220,425.7          5,449,201.1
    1   2020-04-22T06:00:00Z   0   0  ...          3,716,941.5          8,452,012.9          6,541,599.9
    ....
    

    The floats are actually objects, but I need them to be real floats.

    To fix it, referencing @AMC's comment above:

    def coerce_to_float(val):
        try:
           return float(val)
        except ValueError:
           return val
    
    df = df.applymap(lambda x: coerce_to_float(x))
    

提交回复
热议问题