Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose only few columns and rows from a dataframe

I am looking to transpose only certain columns in my dataframe and their values by keeping starting columns fixed.

I/P frame:

Type    Class   24/01/2018  25/01/2018  26/01/2018
Plant1  Plant   5498    5998    5815
Plant2  Plant   3416    4844    4991
Veg1    Vegetable   5426    5464    3756
Veg2    Vegetable   5317    4616    7528

O/P frame:

Type    Class   Value   Date
Plant1  Plant   5498    24/01/2018
Plant1  Plant   5998    25/01/2018
Plant1  Plant   5815    26/01/2018
Veg1    Vegetable   5426    24/01/2018
Veg1    Vegetable   5464    25/01/2018
Veg1    Vegetable   3756    26/01/2018

I normally do this in excel, and tried using pivot in pandas but unable to get an idea to implement it. Can anyone help in giving me a lead?

Thanks

like image 860
Shahrukh Khalidi Avatar asked Dec 10 '22 06:12

Shahrukh Khalidi


1 Answers

melt

df.melt(['Type', 'Class'], var_name='Date', value_name='Value')

      Type      Class        Date  Value
0   Plant1      Plant  24/01/2018   5498
1   Plant2      Plant  24/01/2018   3416
2     Veg1  Vegetable  24/01/2018   5426
3     Veg2  Vegetable  24/01/2018   5317
4   Plant1      Plant  25/01/2018   5998
5   Plant2      Plant  25/01/2018   4844
6     Veg1  Vegetable  25/01/2018   5464
7     Veg2  Vegetable  25/01/2018   4616
8   Plant1      Plant  26/01/2018   5815
9   Plant2      Plant  26/01/2018   4991
10    Veg1  Vegetable  26/01/2018   3756
11    Veg2  Vegetable  26/01/2018   7528

set_index + stack

(df.set_index(['Type', 'Class'])
   .stack()
   .rename_axis(['Type', 'Class', 'Date'])
   .reset_index(name='Value')
)

      Type      Class        Date  Value
0   Plant1      Plant  24/01/2018   5498
1   Plant1      Plant  25/01/2018   5998
2   Plant1      Plant  26/01/2018   5815
3   Plant2      Plant  24/01/2018   3416
4   Plant2      Plant  25/01/2018   4844
5   Plant2      Plant  26/01/2018   4991
6     Veg1  Vegetable  24/01/2018   5426
7     Veg1  Vegetable  25/01/2018   5464
8     Veg1  Vegetable  26/01/2018   3756
9     Veg2  Vegetable  24/01/2018   5317
10    Veg2  Vegetable  25/01/2018   4616
11    Veg2  Vegetable  26/01/2018   7528
like image 135
cs95 Avatar answered Dec 20 '22 01:12

cs95