Given a df
4
0
3
3
3
and reference ndata_time=’2019-01-15 7:00:00′,
I would to create a new column but with an interval of 5sec
4 2019-01-15 7:00.00
0 2019-01-15 7:00.05
3 2019-01-15 7:00.10
3 2019-01-15 7:00.15
3 2019-01-15 7:00.20
However, I am having difficulties of setting the interval_range() function in Pandas.
Appreciate if someone can shed some light.
import pandas as pd
np.random.seed(0)
ndata_time='2019-01-15 7:00:00'
lapse=5 # unit in second
df=pd.DataFrame(np.random.randint(5,size=(5)),columns=['data'])
>Solution :
You’d have to use pd.date_range here. Set period and freq parameter as needed.
periods: int, optional
- Number of periods to generate.
freq: str or DateOffset, default ‘D’
- Frequency strings can have multiples, e.g. ‘5H’. See here for a list of frequency aliases.
pd.date_range(start='2019-01-15 7:00:00', periods=5, freq='5S')
# DatetimeIndex(['2019-01-15 07:00:00', '2019-01-15 07:00:05',
# '2019-01-15 07:00:10', '2019-01-15 07:00:15',
# '2019-01-15 07:00:20'],
# dtype='datetime64[ns]', freq='5S')