zuy007
zuy007

Reputation: 37

Create a date column for dataframe

I have a dataframe of numeric sequence as show below:

  power
0  0.434083
1  0.225000
2  1.202458
3  0.672167
4  0.634708

I want to create a date column and make it the index - transform the sequence data into time-series data.

I tried the following piece of code:

import datetime
 
todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date, periods=5, freq='D')
 
columns = df['power']
 
new = pd.DataFrame(index=index, columns=columns)

print(new.head())

But no avail. I keep getting this error:

File "", line 2

^

SyntaxError: invalid character in identifier

Thanks in advance.

Upvotes: 1

Views: 75

Answers (1)

jezrael
jezrael

Reputation: 862641

You can use to_datetime here with origin and unit parameters:

import datetime
 
todays_date = datetime.datetime.now()
df.index = pd.to_datetime(df.index, origin=todays_date, unit='d')
print (df)
               power
2021-01-21  0.434083
2021-01-22  0.225000
2021-01-23  1.202458
2021-01-24  0.672167
2021-01-25  0.634708

Upvotes: 2

Related Questions