Iterate through dataframe to extract delta of a particular time period - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Iterate through dataframe to extract delta of a particular time period (/thread-30458.html) |
Iterate through dataframe to extract delta of a particular time period - lynnette1983 - Oct-21-2020 I have a file, df, that I wish to take the delta of every 7 day period and reflect the timestamp for that particular period df: Date Value 10/15/2020 75 10/14/2020 70 10/13/2020 65 10/12/2020 60 10/11/2020 55 10/10/2020 50 10/9/2020 45 10/8/2020 40 10/7/2020 35 10/6/2020 30 10/5/2020 25 10/4/2020 20 10/3/2020 15 10/2/2020 10 10/1/2020 5 **Desired Output:** Date Value 10/9/2020 30 10/2/2020 30 10/15/2020 to 10/9/2020 is 7 days with the delta being: 75 - 45 = 30 10/9/2020 timestamp would be: 30 and so on This is what I am doing: for row in df.itertuples(): callDate = datetime.strptime(row.Date, "%m/%d/%y %I:%M %p") previousRecord = df['Date'].shift(-6).strptime(row.Date, "%m/%d/%y %I:%M %p") Delta = Date - previousRecord I am thinking I may be able to do this as well: df=df.assign(Delta=df.Sun.sub(df.Monday),Date=pd.Series\ (pd.date_range(pd.Timestamp('2020-01-01'), periods=7, freq='7d')))[ [['Delta','Date']] Any suggestion is appreciated RE: Iterate through dataframe to extract delta of a particular time period - scidam - Oct-22-2020 Since rows corresponds days you can just shift the data frame on 6 positions and compute difference between shifted and original ones: (df.shift(6).iloc[:, 1] - df.iloc[:,1])[df.index % 6 == 0].dropna() |