Create pandas dataframe from datetime range

Viewed 2018

I currently have a data that ranges from 2020-11-03 to 2021-10-01.

I want to make a new dataframe where the row value is equal to the date.

To clarify the first row of the datafame would be 2020-11-03 and the second row would be 2020-11-04 and so on.

Would there be a way to create a new dataframe where the rows would be every single date between that given range?

I am planning on mapping the other values later on, so I currently just need a new dataframe that has just one column.

Thank you in advance!!

2 Answers

You can use the pandas function date_range (documentation here) and pass your desired date strings to the start and end arguments (and the default frequency is 1 day):

df = pd.DataFrame({'date':pd.date_range(start='2020-11-03', end='2021-10-01')})

Output:

>>> df
          date
0   2020-11-03
1   2020-11-04
2   2020-11-05
3   2020-11-06
4   2020-11-07
..         ...
328 2021-09-27
329 2021-09-28
330 2021-09-29
331 2021-09-30
332 2021-10-01

[333 rows x 1 columns]

Pandas implemented the DatetimeIndex class that you can instantiate with pandas.date_range function.

import pandas as pd
pd.date_range(start='2020-11-03', end='2021-10-01')
DatetimeIndex(['2020-11-03', '2020-11-04', '2020-11-05', '2020-11-06',
               '2020-11-07', '2020-11-08', '2020-11-09', '2020-11-10',
               '2020-11-11', '2020-11-12',
               ...
               '2021-09-22', '2021-09-23', '2021-09-24', '2021-09-25',
               '2021-09-26', '2021-09-27', '2021-09-28', '2021-09-29',
               '2021-09-30', '2021-10-01'],
              dtype='datetime64[ns]', length=333, freq='D')

If you really need a DataFrame from that range you can just create one from the previous:

pd.DataFrame(pd.date_range(start='2020-11-03', end='2021-10-01'), columns=['dates'])

Reference: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html

Related