Home > Back-end >  Pandas / Google Colab / How to get multiple output in a cell with exception?
Pandas / Google Colab / How to get multiple output in a cell with exception?

Time:06-26

In my Google Colab I would like to parse a date Serie and print the one's the parser can't handle (the two last in my case)

ser = pd.Series(['01 Jan 2010', '02-02-2011', '20120303', '2013/04/04', '2014-05-05','2015120','2014120'])
ser

enter image description here

And here is my code

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from dateutil.parser import parse
print("before try")
try :
  print("inside try")
  print(ser.map(lambda x : parse(x)))
except Exception as e :
  print(e)

The problem is : it just print the first error

enter image description here

CodePudding user response:

I fixed this situation with a helper function as follows.

def my_parser(x):
    try:
        return parse(x)
    except Exception as e:
        return e

I edited it as follows.

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from dateutil.parser import parse
print(ser.map(lambda x : my_parser(x)))

I hope it helped.

CodePudding user response:

ser = pd.Series(['01 Jan 2010', '02-02-2011', '20120303', '2013/04/04', '2014-05-05','2015120','2014120'])
parsed = pd.to_datetime(ser, 'coerce')
print(parsed)
print(ser[parsed.isna()])

Output:

0   2010-01-01
1   2011-02-02
2   2012-03-03
3   2013-04-04
4   2014-05-05
5          NaT
6          NaT
dtype: datetime64[ns]
5    2015120
6    2014120
dtype: object
  • Related