Converting strings to floats in a DataFrame

前端 未结 6 812
无人及你
无人及你 2020-11-27 12:30

How to covert a DataFrame column containing strings and NaN values to floats. And there is another column whose values are strings and floats; how to convert th

6条回答
  •  攒了一身酷
    2020-11-27 12:51

    In a newer version of pandas (0.17 and up), you can use to_numeric function. It allows you to convert the whole dataframe or just individual columns. It also gives you an ability to select how to treat stuff that can't be converted to numeric values:

    import pandas as pd
    s = pd.Series(['1.0', '2', -3])
    pd.to_numeric(s)
    s = pd.Series(['apple', '1.0', '2', -3])
    pd.to_numeric(s, errors='ignore')
    pd.to_numeric(s, errors='coerce')
    

提交回复
热议问题