I have a Pandas DataFrame:
import pandas as pd
df = pd.DataFrame([['A', '2014-01-01', '2014-01-07', 1.2],
['B', '2014-01-01', '2014-01-07', 2.5],
['C', '2014-01-01', '2014-01-07', 3.],
['A', '2014-01-08', '2014-01-14', 13.],
['B', '2014-01-08', '2014-01-14', 2.],
['C', '2014-01-08', '2014-01-14', 1.],
['A', '2014-01-15', '2014-01-21', 10.],
['A', '2014-01-21', '2014-01-27', 98.],
['B', '2014-01-21', '2014-01-27', -5.],
['C', '2014-01-21', '2014-01-27', -72.],
['A', '2014-01-22', '2014-01-28', 8.],
['B', '2014-01-22', '2014-01-28', 25.],
['C', '2014-01-22', '2014-01-28', -23.],
['A', '2014-01-22', '2014-02-22', 8.],
['B', '2014-01-22', '2014-02-22', 25.],
['C', '2014-01-22', '2014-02-22', -23.],
], columns=['Group', 'Start Date', 'End Date', 'Value'])
And the output looks like this:
Group Start Date End Date Value
0 A 2014-01-01 2014-01-07 1.2
1 B 2014-01-01 2014-01-07 2.5
2 C 2014-01-01 2014-01-07 3.0
3 A 2014-01-08 2014-01-14 13.0
4 B 2014-01-08 2014-01-14 2.0
5 C 2014-01-08 2014-01-14 1.0
6 A 2014-01-15 2014-01-21 10.0
7 A 2014-01-21 2014-01-27 98.0
8 B 2014-01-21 2014-01-27 -5.0
9 C 2014-01-21 2014-01-27 -72.0
10 A 2014-01-22 2014-01-28 8.0
11 B 2014-01-22 2014-01-28 25.0
12 C 2014-01-22 2014-01-28 -23.0
13 A 2014-01-22 2014-02-22 8.0
14 B 2014-01-22 2014-02-22 25.0
15 C 2014-01-22 2014-02-22 -23.0
I am trying to add a new column with data from the same group in the previous period (if it exists). So, the output should look like this:
Group Start Date End Date Value Last Period Value
0 A 2014-01-01 2014-01-07 1.2 NaN
1 B 2014-01-01 2014-01-07 2.5 NaN
2 C 2014-01-01 2014-01-07 3.0 NaN
3 A 2014-01-08 2014-01-14 13.0 1.2
4 B 2014-01-08 2014-01-14 2.0 2.5
5 C 2014-01-08 2014-01-14 1.0 3.0
6 A 2014-01-15 2014-01-21 10.0 13.0
7 A 2014-01-21 2014-01-27 98.0 NaN
8 B 2014-01-21 2014-01-27 -5.0 NaN
9 C 2014-01-21 2014-01-27 -72.0 NaN
10 A 2014-01-22 2014-01-28 8.0 10.0
11 B 2014-01-22 2014-01-28 25.0 NaN
12 C 2014-01-22 2014-01-28 -23.0 NaN
13 A 2014-01-22 2014-02-22 8.0 NaN
14 B 2014-01-22 2014-02-22 25.0 NaN
15 C 2014-01-22 2014-02-22 -23.0 NaN
Notice that the rows with NaN do not have a corresponding value with the same group and that is in the last period. So, rows that span 7 days (one week) need to be matched with the same row with the same group but from the previous week.