Pandas: creating a datime index from scratch

Viewed 45

I guess this is a pretty basic question but I could not find any answer elsewhere.

Let's assume I have a dataframe:

df = pd.DataFrame({'c1':[1,2,3],'c2':[4,5,6]})
print(df)

        c1     c2
0       1      4 
1       2      5
2       3      6

I basically want to create an hourly datetime index starting from a specific date that would be corresponding to the first row. Let us say for the sake of the example that the first row corresponds to '2020-01-01 00:00'. the second row would then be '2020-01-01 01:00' and so on for the subsequent rows. How can I create such a datetime index?

Many thanks,

1 Answers

You can use date_range:

df.index = pd.date_range('2020-01-01', freq='H', periods=len(df))

Output:

                     c1  c2
2020-01-01 00:00:00   1   4
2020-01-01 01:00:00   2   5
2020-01-01 02:00:00   3   6
Related