I have a dataframe df
as follows:
Year | Month | Rate | |
---|---|---|---|
0 | 2022 | 1 | 0.1 |
1 | 2022 | 2 | 0.1 |
2 | 2022 | 3 | 0.1 |
3 | 2022 | 4 | 0.1 |
4 | 2022 | 5 | 0.1 |
5 | 2022 | 6 | 0.1 |
6 | 2022 | 7 | 0.1 |
7 | 2022 | 8 | 0.1 |
8 | 2022 | 9 | 0.1 |
9 | 2022 | 10 | 0.1 |
10 | 2022 | 11 | 0.1 |
11 | 2022 | 12 | 0.1 |
12 | 2023 | 1 | 0.2 |
13 | 2023 | 2 | 0.2 |
14 | 2023 | 3 | 0.2 |
15 | 2023 | 4 | 0.2 |
16 | 2023 | 5 | 0.2 |
17 | 2023 | 6 | 0.2 |
18 | 2023 | 7 | 0.2 |
19 | 2023 | 8 | 0.2 |
20 | 2023 | 9 | 0.2 |
21 | 2023 | 10 | 0.2 |
22 | 2023 | 11 | 0.2 |
23 | 2023 | 12 | 0.2 |
I need to get the years as the column headers, so I ran the following code:
result = df.groupby([df.Month, df.Year]).sum().unstack()
Output:
| | Rate | |
|———–|———-|———-|
| Year | 2022 | 2023 |
| Month | | |
| 1 | 0.1 | 0.2 |
| 2 | 0.1 | 0.2 |
| 3 | 0.1 | 0.2 |
| 4 | 0.1 | 0.2 |
| 5 | 0.1 | 0.2 |
| 6 | 0.1 | 0.2 |
| 7 | 0.1 | 0.2 |
| 8 | 0.1 | 0.2 |
| 9 | 0.1 | 0.2 |
| 10 | 0.1 | 0.2 |
| 11 | 0.1 | 0.2 |
| 12 | 0.1 | 0.2 |
When I try to reset the index and clean up the headers, reset_index()
does not seem to be working.
Here is the code I tried :
result.columns = result.columns.droplevel(0)
result.reset_index(inplace = True)
result.reset_index( drop = True)
print(result)
Output:
| Year | Month | 2022 | 2023 |
|———:|——:|—–:|—–:|
| 0 | 1 | 0.1 | 0.2 |
| 1 | 2 | 0.1 | 0.2 |
| 2 | 3 | 0.1 | 0.2 |
| 3 | 4 | 0.1 | 0.2 |
| 4 | 5 | 0.1 | 0.2 |
| 5 | 6 | 0.1 | 0.2 |
| 6 | 7 | 0.1 | 0.2 |
| 7 | 8 | 0.1 | 0.2 |
| 8 | 9 | 0.1 | 0.2 |
| 9 | 10 | 0.1 | 0.2 |
| 10 | 11 | 0.1 | 0.2 |
| 11 | 12 | 0.1 | 0.2 |
I would like to get rid of Year
as the index but whatever I try, I can’t seem to get to this or even rename it to nothing
I even tried df.pivot
but I run into the same problem