If I have a DataFrame:
myDF = DataFrame(data=[[11,11],[22,'2A'],[33,33]], columns = ['A','B'])
Gives the next data frame (starting with stackoverflow and not having enough reputation for a DataFrame image)
| A | B |
0 | 11 | 11 |
1 | 22 | 2A |
2 | 33 | 33 |
If I want to convert column B values ββto int and drop values ββthat cannot be converted, I have to do:
def convertToInt(cell):
try:
return int(cell)
except:
return None
myDF['B'] = myDF['B'].apply(convertToInt)
If I just do:
myDF ['B']. Apply (integer)
obviously the error is:
C: \ WinPython-32bit-2.7.5.3 \ python-2.7.5 \ lib \ site-packages \ pandas \ lib.pyd in pandas.lib.map_infer (pandas \ lib.c: 42840) ()
ValueError: invalid literal for int () with base 10: '2A'
Is there a way to add exception handling to myDF ['B']. apply ()
Thank you in advance!
source
share