Ignore errors in pandas astype

后端 未结 1 808
抹茶落季
抹茶落季 2020-12-07 01:47

I have a numeric column that could contain another characters different form [0-9]. Say: x = pandas.Series([\"1\",\"1.2\", \"*\", \"1\", \"**.\"])

相关标签:
1条回答
  • 2020-12-07 01:56

    I think you want to use pd.to_numeric(x, errors='coerce') instead:

    In [73]: x = pd.to_numeric(x, errors='coerce')
    
    In [74]: x
    Out[74]:
    0    1.0
    1    1.2
    2    NaN
    3    1.0
    4    NaN
    dtype: float64
    

    PS actually x.astype(dtype = float, errors = 'ignore') - works as expected, it doesn't give an error, it just leaves series as it is as it can't convert some elements:

    In [77]: x.astype(dtype = float, errors = 'ignore')
    Out[77]:
    0      1
    1    1.2
    2      *
    3      1
    4    **.
    dtype: object   # <----- NOTE!!!
    
    In [81]: x.astype(dtype = float, errors = 'ignore').tolist()
    Out[81]: ['1', '1.2', '*', '1', '**.']
    
    0 讨论(0)
提交回复
热议问题