Reputation: 351
Pandas newbie here. I want to convert a date range time series date_time from pandas:
import pandas as pd
import numpy as np
In [1]: date_time = pd.date_range('2017/10/27','2017/10/29',freq='12H')
into a numpy array t containing the elapsed time (for instance, in hours), such that:
In [2]: t
Out[2]: array([0,12,24,36,48])
What would be the most direct way to do this?
I need this to pass the numpy array t to odeint routines.
Upvotes: 1
Views: 3100
Reputation: 402493
You could also convert to a pd.Series
and call dt.total_seconds
.
x = pd.Series(date_time)
y = (x - x[0]).dt.total_seconds().div(60 * 60).values
y
array([ 0., 12., 24., 36., 48.])
Upvotes: 1
Reputation: 879511
You can divide Timedeltas by another Timedelta to convert them to a desired frequency unit (such as hours). Use the .values
attribute to convert the result to a NumPy array:
In [37]: ((date_time - date_time[0]) / pd.Timedelta('1H')).values
Out[37]: array([ 0., 12., 24., 36., 48.])
Upvotes: 1