Using datetime timedelta with series in pandas DF

I have pandas sim_df that looks like this:

enter image description here

Now I want to add another column “date”, which corresponds to the date corresponding to “now” plus “cum_days” (delta time).

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

But it seems that deltatime is not using a series, but a fixed scalar.

TypeError: unsupported type for timedelta days component: Series

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

+4
source share
3 answers

How about this?

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

This applies dt.timedeltato each column element cum_daysindividually.

+3
source

Add timedelta now using list comprehension.

sim_df = pd.DataFrame({'delta_time_days': [1.02, .09, 1.08, 1.7, 4.1, 0.3, .13, .01, .3, .7], 
                       'cum_days': [1.1, 1.1, 2.2, 3.9, 8.0, 8.3, 8.4, 8.4, 8.8, 9.5]})

sim_df['date'] = [dt.datetime.now() + dt.timedelta(days=d) for d in sim_df.cum_days]

>>> sim_df
   cum_days  delta_time_days                       date
0       1.1             1.02 2016-02-11 17:36:11.320271
1       1.1             0.09 2016-02-11 17:36:11.320286
2       2.2             1.08 2016-02-12 20:00:11.320289
3       3.9             1.70 2016-02-14 12:48:11.320292
4       8.0             4.10 2016-02-18 15:12:11.320296
5       8.3             0.30 2016-02-18 22:24:11.320299
6       8.4             0.13 2016-02-19 00:48:11.320301
7       8.4             0.01 2016-02-19 00:48:11.320304
8       8.8             0.30 2016-02-19 10:24:11.320306
9       9.5             0.70 2016-02-20 03:12:11.320309
+3

a TimedeltaIndex :

In [26]:
sim_df = pd.DataFrame({'delta_time_days': [1.02, .09, 1.08, 1.7, 4.1, 0.3, .13, .01, .3, .7], 
                       'cum_days': [1.1, 1.1, 2.2, 3.9, 8.0, 8.3, 8.4, 8.4, 8.8, 9.5]})
start = dt.datetime.now()
sim_df['date'] = start + pd.TimedeltaIndex(sim_df['cum_days'], unit='D')
sim_df

Out[26]:
   cum_days  delta_time_days                       date
0       1.1             1.02 2016-02-12 01:40:32.413413
1       1.1             0.09 2016-02-12 01:40:32.413413
2       2.2             1.08 2016-02-13 04:04:32.413413
3       3.9             1.70 2016-02-14 20:52:32.413413
4       8.0             4.10 2016-02-18 23:16:32.413413
5       8.3             0.30 2016-02-19 06:28:32.413413
6       8.4             0.13 2016-02-19 08:52:32.413413
7       8.4             0.01 2016-02-19 08:52:32.413413
8       8.8             0.30 2016-02-19 18:28:32.413413
9       9.5             0.70 2016-02-20 11:16:32.413413
+2

Source: https://habr.com/ru/post/1628212/


All Articles