Exception Handling in Pandas .apply() function

后端 未结 3 1883
忘了有多久
忘了有多久 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:37

    A way to achieve that with lambda:

    myDF['B'].apply(lambda x: int(x) if str(x).isdigit() else None)
    

    For your input:

    >>> myDF
        A   B
    0  11  11
    1  22  2A
    2  33  33
    
    [3 rows x 2 columns]
    

    >>> myDF['B'].apply(lambda x: int(x) if str(x).isdigit() else None)
    0    11
    1   NaN
    2    33
    Name: B, dtype: float64
    

提交回复
热议问题