Transpose a table using python

50 Views Asked by At

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.

3

There are 3 best solutions below

0
Andrej Kesely On BEST ANSWER

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
0
Shirin Yavari On
df = df.set_index('Store').stack().reset_index(name='Sales').rename(columns={'level_1':'Qrt'})
print (df)
0
DavidH On

A concise alternative to the answers already given is

df = df.melt(id_vars="Store", var_name="Qrt", value_name="Sales")

https://pandas.pydata.org/docs/reference/api/pandas.melt.html