I am trying to stack financial values year wise in pandas Dataframe. But not able to get started.
All I have tried is
df1 = df.set_index(['refnum','y1gp','y2gp','y3gp']).stack()\
.reset_index(name='REV').rename(columns={'level_5':'Year'})
Existing:
| refnum | y1 | y1rev | y1gp | y2 | y2rev | y2gp | y3 | y3rev | y3gp |
|---|---|---|---|---|---|---|---|---|---|
| 10001 | 2021 | 300 | 200 | 2022 | 100 | 600 | 2023 | 300 | 300 |
| 10002 | 2020 | 300 | 200 | 2021 | 200 | 500 | 2022 | 300 | 300 |
| 10003 | 2021 | 300 | 200 | 2022 | 500 | 500 | 2023 | 300 | 300 |
Expected:
| refnum | year | REV | GP | Base Year |
|---|---|---|---|---|
| 10001 | 2021 | 300 | 200 | BaseYear |
| 10001 | 2022 | 100 | 600 | BaseYear+1 |
| 10001 | 2023 | 300 | 300 | BaseYear+2 |
| 10002 | 2020 | 300 | 200 | BaseYear |
| 10002 | 2021 | 200 | 500 | BaseYear+1 |
| 10002 | 2022 | 300 | 300 | BaseYear+2 |
| 10003 | 2021 | 300 | 200 | BaseYear |
| 10003 | 2022 | 500 | 500 | BaseYear+1 |
| 10003 | 2023 | 300 | 300 | BaseYear+2 |