Search code examples
pythonpandastranspose

Transpose df.T is not working properly for my df, not sure where im going wrong


my initial data

Date        Copper     Zinc Aluminium US HRC                
2021-04-21  9448.0  2815.0  2377.0  1360.0
2021-04-27  9877.0  2929.0  2398.0  1360.0
%change     5.0     4.0     1.0      0.0

after I transpose using df.T my output was,

            0         1         2
Copper     9448    9876     4.53853
Zinc       2815    2929     4.04973
Aluminium  2377    2398     0.874979
US HRC     1360     1360            0
Date    2021-04-21  2021-04-27  %change

But I want my final output to look like

        2021-04-21 2021-04-27   %change
Copper     9448     9876       4.53853
Zinc       2815     2929       4.04973
Aluminium  2377     2398       0.874979
US HRC     1360     1360            0

Solution

  • Use dt.set_index('Date').T

    After transpose, row index will become column index. So, if you want the column index show the value of Date column, you can make it row index before transpose.

    Demo

    print(df)
    
             Date  Copper    Zinc  Aluminium  US_HRC
    0  2021-04-21  9448.0  2815.0     2377.0  1360.0
    1  2021-04-27  9877.0  2929.0     2398.0  1360.0
    2     %change     5.0     4.0        1.0     0.0
    
    
    print(df.set_index('Date').T)
    
    
    Date       2021-04-21  2021-04-27  %change
    Copper         9448.0      9877.0      5.0
    Zinc           2815.0      2929.0      4.0
    Aluminium      2377.0      2398.0      1.0
    US_HRC         1360.0      1360.0      0.0