I have a df column with text in it and I'm trying to extract different date patterns from it.
This df1 for example:
<index> text
0 My birthday is 10/23/89.
1 Christmas is on December 25th.
2 Thanksgiving of 11/2008 was the best.
The desired output is a 3rd column, called dates:
<index> text dates
0 My birthday is 10/23/89. 10/23/89
1 Christmas is on December 25. 25 December
2 Thanksgiving of 11/2008 was the best. 11/2008
To pull our the first date I write my first re expression, like this one:
df1['dates'] = (df1['text'].str.findall(r'\d{1,2}[/-]\d{1,2}[/-]\d{2,4}'))
And that's where I get stuck.
I don't know/understand how to write multiple re expressions and not keep writing over what's already in the df1['dates'] column.
I'd like to run my next expression:
df1['dates'] = df1['text'].str.findall(r'(?:\d{1,2})?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* (?:\d{1,2}, )?\d{4}')
How, or what is the best way, to see if df['dates'] column is null and then try the next re expression?
I asked this earlier today and it got flagged as a possible duplicate of this but I think DeepSpace thought I was a lot smarter than I really am, my question is much more basic than the one he answered.
You can try
df['dates'] = df['text'].str.extract('.*?(\d+/\d+/?\d*).*?')
text dates
0 My birthday is 10/23/89. 10/23/89
1 Christmas is 12/25. 12/25
2 Thanksgiving of 11/2008 was the best. 11/2008
With the added test case:
df['text'].str.extract('.*?(\d+/\d+/?\d*).*?|\
(January|February|March|April|May|June|July|August|September|October|November|December \d+)', expand = False)\
.fillna('').sum(1)
And you get
0 10/23/89
1 December 25
2 11/2008
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With