Create "buffer" Matrix From Dataframe With Rolling Window?
Given a dataframe of just one column, how can I convert it into another dataframe 'buffer' (of size 2), described below: df = 0 0 1 1 2 2 3 3 4 4 4 5 5 6 5 expected_buff
Solution 1:
import pandas as pd
def buff(s, n):
return (pd.concat([s.shift(-i) for i in range(n)], axis=1)
.dropna().astype(int))
s = pd.Series([1,2,3,4,5])
print(buff(s, 2))
# 0 0
# 0 1 2
# 1 2 3
# 2 3 4
# 3 4 5
print(buff(s, 3))
# 0 0 0
# 0 1 2 3
# 1 2 3 4
# 2 3 4 5
print(buff(s, 4))
# 0 0 0 0
# 0 1 2 3 4
# 1 2 3 4 5
Solution 2:
def buff(df, past):
a = np.concatenate([df.values[i:i-past] for i in range(past)], axis=1)
return pd.DataFrame(a, columns=list(range(past)))
buff(df, 2)
buff(df, 3)
buff(df, 4)
buff(df, 5)
Post a Comment for "Create "buffer" Matrix From Dataframe With Rolling Window?"