Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas method chaining pd.to_datetime() through .assign()

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

like image 473
Robert Chestnutt Avatar asked Dec 13 '25 23:12

Robert Chestnutt


2 Answers

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']))
        )
like image 151
Adam Montgomery Avatar answered Dec 16 '25 21:12

Adam Montgomery


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']))
like image 24
Robert Chestnutt Avatar answered Dec 16 '25 23:12

Robert Chestnutt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!