Change column type in pandas

前端 未结 9 1287
萌比男神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:10

    Here is a function that takes as its arguments a DataFrame and a list of columns and coerces all data in the columns to numbers.

    # df is the DataFrame, and column_list is a list of columns as strings (e.g ["col1","col2","col3"])
    # dependencies: pandas
    
    def coerce_df_columns_to_numeric(df, column_list):
        df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')
    

    So, for your example:

    import pandas as pd
    
    def coerce_df_columns_to_numeric(df, column_list):
        df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')
    
    a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
    df = pd.DataFrame(a, columns=['col1','col2','col3'])
    
    coerce_df_columns_to_numeric(df, ['col2','col3'])
    

提交回复
热议问题