Having the following datatable:
import datetime as dt
import pandas as pd
some_money = [34,42,300,450,550]
df = pd.DataFrame({'TIME': ['2020-01', '2019-12', '2019-11', '2019-10', '2019-09'], \
'MONEY':some_money})
for x in range(1,4):
df[f'period (-{x})'] = df["MONEY"].shift(periods = -x, fill_value = 0)
df
creating this output:
How do I put the columns on an arbitrary position upon creating them?
I have read how do I insert a column at a specific column index in pandas? and I managed to put them wherever I want with the following snippet:
cols = df.columns.tolist()
print(cols)
cols = ['TIME', 'period (-1)','MONEY', 'period (-2)', 'period (-3)']
df.reindex(columns=cols)
but, creating the cols
list seems like a bit of a manual effort. Is there a way to decide upon the for x in range(1,4)
loop where to put the columns? Somehow producing the table below from the code, producing the datatable: