I am trying to make many new columns only by shifting the 'amount_in_group_currency' column, here is my approach:
pay_history_by_interv = (temp.assign(due_amount= temp['amount_in_group_currency'])
.assign(period_1= temp['amount_in_group_currency'].shift(1))
.assign(period_2= temp['amount_in_group_currency'].shift(2))
.assign(period_3= temp['amount_in_group_currency'].shift(3))
.assign(period_4= temp['amount_in_group_currency'].shift(4))
.assign(period_5= temp['amount_in_group_currency'].shift(5))
.assign(period_6= temp['amount_in_group_currency'].shift(6))
.drop('amount_in_group_currency', axis=1).fillna(0).reset_index()
)
This works for a small number of shifts (e.g 6 in my case) but not for much more, is there a "pandas way" to automate this column making shifts with any desired number?
Thank you
CodePudding user response:
If the question is how to automate creation of columns so you do not have to type them by hand for each one, you can use a loop
n_shifts = 10 # specify how many shifts you want
for n in range(n_shifts):
temp[f'period_{n 1}'] = temp['amount_in_group_currency'].shift(n 1)
pay_history_by_interv = temp.drop('amount_in_group_currency', axis=1).fillna(0).reset_index()
