Remove rows where column value type is string Pandas

前端 未结 4 2010
暗喜
暗喜 2020-12-17 10:21

I have a pandas dataframe. One of my columns should only be floats. When I try to convert that column to floats, I\'m alerted that there are strings in there. I\'d like to d

4条回答
  •  自闭症患者
    2020-12-17 10:59

    One of my columns should only be floats. I'd like to delete all rows where values in this column are strings

    You can convert your series to numeric via pd.to_numeric and then use pd.Series.notnull. Conversion to float is required as a separate step to avoid your series reverting to object dtype.

    # Data from @EdChum
    
    df = pd.DataFrame({'a': [0.1, 0.5, 'jasdh', 9.0]})
    
    res = df[pd.to_numeric(df['a'], errors='coerce').notnull()]
    res['a'] = res['a'].astype(float)
    
    print(res)
    
         a
    0  0.1
    1  0.5
    3  9.0
    

提交回复
热议问题