Im trying, with no luck, to method chain pd.to_datetime() through .assign()
This works:
tcap2 = tcap.\
assign(person = tcap['text'].apply(lambda x: x.split(" ", 1)[0]),
date_time = tcap['text'].str.extract(r'\(([^()]+)\)'),
text = tcap['text'].str.split(': ').str[1])
tcap2['date_time'] = pd.to_datetime(tcap2['date_time'])
but I was hoping to have the whole chunk in the same chain like this:
tcap2 = tcap.\
assign(person = tcap['text'].apply(lambda x: x.split(" ", 1)[0]),
date_time = tcap['text'].str.extract(r'\(([^()]+)\)'),
text = tcap['text'].str.split(': ').str[1]).\
assign(date_time = lambda df: pd.to_datetime(tcap['date_time']))
I would be grateful for any advice
On a separate note, to avoid the use of '\' and to make chaining like this more readable you can surround the expression with parentheses:
tcap = (tcap
.assign(person=tcap['text'].apply(lambda x: x.split(" ", 1)[0]),
date_time=tcap['text'].str.extract(r'\(([^()]+)\)'),
text=tcap['text'].str.split(': ').str[1])
.assign(date_time = lambda tcap: pd.to_datetime(tcap['date_time']))
)
Thank you Nipy you are awesome, just a little change there in my lambda function (facepalm) This worked an absolute treat and just makes the code so much more compact and readable
tcap = tcap.\
assign(person = tcap['text'].apply(lambda x: x.split(" ", 1)[0]),
date_time = tcap['text'].str.extract(r'\(([^()]+)\)'),
text = tcap['text'].str.split(': ').str[1]).\
assign(date_time = lambda tcap: pd.to_datetime(tcap['date_time']))
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