I have a dataframe with on column, I want to add another columns which shows the timestamp. I want the increasing time as 5 min. Here is an example:
import pandas as pd df = pd.DataFrame() df['value'] = [57,43, 55, 64]
The data frame which i want is like this:
Could you please help how to build a df like that? Thanks
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use date_range.
As index:
df = df.set_index(pd.date_range('2015-02-26 21:42:53', freq='5min', periods=len(df)))
output:
value 2015-02-26 21:42:53 57 2015-02-26 21:47:53 43 2015-02-26 21:52:53 55 2015-02-26 21:57:53 64
With index name:
df = df.set_index(pd.date_range('2015-02-26 21:42:53',
freq='5min',
periods=len(df)).rename('timestamp'))
output:
value timestamp 2015-02-26 21:42:53 57 2015-02-26 21:47:53 43 2015-02-26 21:52:53 55 2015-02-26 21:57:53 64
As new column:
df['date'] = pd.date_range('2015-02-26 21:42:53', freq='5min', periods=len(df))
output:
value date 0 57 2015-02-26 21:42:53 1 43 2015-02-26 21:47:53 2 55 2015-02-26 21:52:53 3 64 2015-02-26 21:57:53
Method 2
import datetime base = datetime.datetime.today() date_list = [str(base - datetime.timedelta(minutes=x)) for x in range(5, 100, 5)] df['date'] = date_list
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0
