Change column type in pandas

前端 未结 9 1286
萌比男神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 05:01

    When I've only needed to specify specific columns, and I want to be explicit, I've used (per DOCS LOCATION):

    dataframe = dataframe.astype({'col_name_1':'int','col_name_2':'float64', etc. ...})
    

    So, using the original question, but providing column names to it ...

    a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
    df = pd.DataFrame(a, columns=['col_name_1', 'col_name_2', 'col_name_3'])
    df = df.astype({'col_name_2':'float64', 'col_name_3':'float64'})
    

提交回复
热议问题