Exception Handling in Pandas .apply() function

后端 未结 3 1884
忘了有多久
忘了有多久 2021-02-18 16:15

If I have a DataFrame:

myDF = DataFrame(data=[[11,11],[22,\'2A\'],[33,33]], columns = [\'A\',\'B\'])

Gives the following dataframe (Starting ou

3条回答
  •  难免孤独
    2021-02-18 16:52

    much better/faster to do:

    In [1]: myDF = DataFrame(data=[[11,11],[22,'2A'],[33,33]], columns = ['A','B'])
    
    In [2]: myDF.convert_objects(convert_numeric=True)
    Out[2]: 
        A   B
    0  11  11
    1  22 NaN
    2  33  33
    
    [3 rows x 2 columns]
    
    In [3]: myDF.convert_objects(convert_numeric=True).dtypes
    Out[3]: 
    A      int64
    B    float64
    dtype: object
    

    This is a vectorized method of doing just this. The coerce flag say to mark as nan anything that cannot be converted to numeric.

    You can of course do this to a single column if you'd like.

提交回复
热议问题