1

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:

enter image description here

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:

enter image description here

Pasha
  • 6,298
  • 2
  • 22
  • 34
Vityata
  • 42,633
  • 8
  • 55
  • 100

1 Answers1

1

Use DataFrame.insert for set to some position, here always to first, but is necessary change order of range by reversed:

for x in reversed(range(1,4)):
    df.insert(1, f'period (-{x})', df["MONEY"].shift(periods = -x, fill_value = 0))

Or by range(4, 1, -1):

for x in range(4, 1, -1):
    df.insert(1, f'period (-{x})', df["MONEY"].shift(periods = -x, fill_value = 0))

print (df)
      TIME  period (-1)  period (-2)  period (-3)  MONEY
0  2020-01           42          300          450     34
1  2019-12          300          450          550     42
2  2019-11          450          550            0    300
3  2019-10          550            0            0    450
4  2019-09            0            0            0    550

If not changed order:

for x in range(1,4):
    df.insert(1, f'period (-{x})', df["MONEY"].shift(periods = -x, fill_value = 0))

print (df)
      TIME  period (-3)  period (-2)  period (-1)  MONEY
0  2020-01          450          300           42     34
1  2019-12          550          450          300     42
2  2019-11            0          550          450    300
3  2019-10            0            0          550    450
4  2019-09            0            0            0    550
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252