Change column type in pandas

前端 未结 9 1298
萌比男神i
萌比男神i 2020-11-21 04:15

I want to convert a table, represented as a list of lists, into a Pandas DataFrame. As an extremely simplified example:

a = [[\'a\', \'1.2\', \'         


        
9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 04:51

    How about this?

    a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
    df = pd.DataFrame(a, columns=['one', 'two', 'three'])
    df
    Out[16]: 
      one  two three
    0   a  1.2   4.2
    1   b   70  0.03
    2   x    5     0
    
    df.dtypes
    Out[17]: 
    one      object
    two      object
    three    object
    
    df[['two', 'three']] = df[['two', 'three']].astype(float)
    
    df.dtypes
    Out[19]: 
    one       object
    two      float64
    three    float64
    

提交回复
热议问题