I have a pandas df like this:
x y
1 0
5 1
3 0
2 0
5 1
6 0
1 0
4 0
3 1
I'm trying to create a new column that takes makes a list of the last 2, current, and next 2 elements in x and y. It should look like this:
x y seq
1 0 [(nan, nan), (nan, nan), (1, 0), (5,1), (3,0)]
5 1 [(nan, nan), (1, 0), (5, 1), (3,0), (2,0)]
3 0 [(1, 0), (5, 1), (3, 0), (2,0), (5,1)]
2 0 [(5, 1), (3, 0), (2, 0), (5,1), (6,0)]
5 1 [(3, 0), (2, 0), (5, 1), (6,0), (nan, nan)]
6 0 [(2, 0), (5, 1), (6, 0), (nan, nan),(nan, nan)]
I wrote this:
def sequences(df):
back2 = (df.x.shift(2), df.y.shift(2))
back1 = (df.x.shift(1), df.y.shift(1))
current = (df.x, df.y)
forward1 = (df.x.shift(-1), df.y.shift(-1))
forward2 = (df.x.shift(-2), df.y.shift(-2))
return [back2, back1, current, forward1, forward2]
df['data_sequence'] = df.apply(sequences, axis=1)
but .shift() fails in df.apply() because it treats each item like an int, not an element in a series. How do I accomplish this?