Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using datetime timedelta with a series in a pandas DF

I have a pandas sim_df that looks like this:

enter image description here

Now, I want to add another column, "date" that is the date corresponding to 'now' plus 'cum_days' (a delta time).

start = dt.datetime.now()
sim_df['date'] = start + dt.timedelta(sim_df['cum_days'])

But it looks like deltatime does not use a series, but a fixed scalar.

TypeError: unsupported type for timedelta days component: Series

Is there a way to solve this in a vectorized operation without iterating over each row of sim_df?

like image 429
Luis Miguel Avatar asked Feb 10 '16 22:02

Luis Miguel


People also ask

How do I convert datetime to Timedelta in pandas?

The to_timedelta() function is used to convert argument to datetime. Timedeltas are absolute differences in times, expressed in difference units (e.g. days, hours, minutes, seconds). This method converts an argument from a recognized timedelta format / value into a Timedelta type. The data to be converted to timedelta.

How do you handle time series data with ease?

Using pandas datetime properties. Initially, the values in datetime are character strings and do not provide any datetime operations (e.g. extract the year, day of the week,…). By applying the to_datetime function, pandas interprets the strings and convert these to datetime (i.e. datetime64[ns, UTC] ) objects.

Does pandas support time series?

pandas contains extensive capabilities and features for working with time series data for all domains. Using the NumPy datetime64 and timedelta64 dtypes, pandas has consolidated a large number of features from other Python libraries like scikits.


1 Answers

How about this?

start = dt.datetime.now()
sim_df['date'] = start + sim_df['cum_days'].map(dt.timedelta)

This applies dt.timedelta to each element of the cum_days column individually.

like image 196
Kris Avatar answered Sep 21 '22 21:09

Kris