简体   繁体   中英

Add “days_since_epoch” column to Pandas TimeSeries DataFrame

A DataFrame has Date as Index. I need to add a column, value of the column should be days_since_epoch. This value can be calculated with

(date_value - datetime.datetime(1970,1,1)).days

How can this value be calculated for all rows in dataframe ?

Following code demonstrate the operation with a sample DataFrame, is there a better way of doing this ?

import pandas as pd
date_range = pd.date_range(start='1/1/1970', end='12/31/2018', freq='D')
df = pd.DataFrame(date_range, columns=['date'])
df['days_since_epoch']=range(0,len(df))
df = df.set_index('date')

Note : this is an example, dates in DataFrame need not start from 1st Jan 1970.

Datetimeindex标量中减去,然后调用TimedeltaIndex.days

df['days_since_epoch1']= (df.index - pd.Timestamp('1970-01-01')).days

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM