EN VI

Transpose a table using python?

2024-03-13 09:30:05
How to Transpose a table using python

I have this table that I need to transpose it in a very specific way using Python:

enter image description here

But I need to transpose it this following way:

enter image description here

Meaning to transpose the headers except for the first column and then the first row with the first value on the first column, then repeat for all stores.

Solution:

Try:

df = (
    df.set_index("Store")
    .stack()
    .rename("Sales")
    .rename_axis(["Store", "Qrt"])
    .reset_index()
)
print(df)

Prints:

      Store       Qrt  Sales
0   Store 1  FQ2 2022   0.51
1   Store 1  FQ4 2022   0.53
2   Store 1  FQ2 2023   0.70
3   Store 1  FQ4 2023   0.74
4   Store 2  FQ2 2022   0.65
5   Store 2  FQ4 2022   0.65
6   Store 2  FQ2 2023   0.33
7   Store 2  FQ4 2023   0.34
8   Store 3  FQ2 2022   0.56
9   Store 3  FQ4 2022   0.76
10  Store 3  FQ2 2023   0.67
11  Store 3  FQ4 2023   0.33
12  Store 4  FQ2 2022   0.58
13  Store 4  FQ4 2022   0.77
14  Store 4  FQ2 2023   0.67
15  Store 4  FQ4 2023   0.30
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login