Pandas数据格式转换 (string to float)

629 阅读1分钟

string to float

1. astype

  • 可多列多格式同进行转换

  • 不适合处理脏数据,不能强制转换(出现格式错误报错、返回原格式)

    df = df.astype({'records' : str, 
        'temperature': float, 
        'frequency': float, 
        'value': str},  copy=True, errors='raise')
    

2. to_numeric

  • 可强制转换

  • 只可单列转换

    df ['Price'] = pd.to_numeric(df['Price'], errors='coerce')		
    
  • 多列转换需要借助apply方法

    cols = data_table.columns[2:-2]
    data_table[cols] = data_table.apply(pd.to_numeric, errors='coerce')