Python delta for 7 day difference

Viewed 168

I have a dataframe, df, that I am wanting to calculate the delta over a 7 day time period:

  Monday   Tuesday   Wednesday   Thursday   Friday    Sat     Sun   

  5        10         15         20         25        30      35

  1        2          3           4         5         6       7

I would like to find the delta for the first row, starting with Monday (5) and ending on Sun (35)

The delta for the first 7 day time period would be: 35 - 5 = 30

The next 7 day window delta would be: 7 - 1 = 6 and so on

The date would begin on 1/1/2020 and continue by 7 day or weekly increments.

Desired output: (New dataframe with the newly created Date and Delta columns)

   Date                  Delta

   1/1/2020              30
   1/8/2020              6

This is what I am doing:

  import pandas as pd
  import numpy as np

  df = pd.read_csv('df.csv')

  df['Delta'] = df['Sunday'] - df['Monday]
  df['Date'] = pd.date_range(start='1/1/2020', periods=len(df), freq='Weeks')




 df2.to_csv('df2.csv')

Any suggestion is appreciated

2 Answers
# necessary imports
import datetime
import pandas

Can do:

numdays=5
base = datetime.datetime(2020,1,1)
date_list = [base + datetime.timedelta(days=7*x) for x in range(numdays)]

Then:

df=pd.DataFrame({'Date':date_list})

If you have another list of values, ie Deltas_list you want to include in this dataframe:

Deltas_list=[0,1,2,3,4]
Deltas=pd.Series(Deltas_list)
df['Delta']=Deltas

df will be:

    Date    Delta
0   2020-01-01  0
1   2020-01-08  1
2   2020-01-15  2
3   2020-01-22  3
4   2020-01-29  4

Lets Try calculate date_range by incorporating multiples in the freq

df['Delta']=df.Sun.sub(df.Monday)
df['Date']=pd.Series(pd.date_range(pd.Timestamp('2020-01-01'), periods=7, freq='7d'))

or simply

df=df.assign(Delta=df.Sun.sub(df.Monday),Date=pd.Series\
(pd.date_range(pd.Timestamp('2020-01-01'), periods=7, freq='7d')))



  Monday  Tuesday  Wednesday  Thursday  Friday  Sat  Sun  Delta       Date
0       5       10         15        20      25   30   35     30    2020-01-01
1       1        2          3         4       5    6    7      6     2020-01-08
Related