Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - Column Header to Row value

I'm trying to achieve the transformation below on a pandas DataFrame. The Date columns are essentially being expanded to multiple rows and we get an entry per month instead of one column per month:

Source DataFrame:

    Food    Type       Eaten 2018-01    Eaten 2018-02   Eaten 2018-03
0   Apple   Fruit      3                4               0
1   Pizza   Fast Food  2                1               3
2   Cake    Desert     3                6               7

Target DataFrame:

        Food    Type        Month      Eaten
0       Apple   Fruit       2018-01    3
1       Apple   Fruit       2018-02    4
2       Apple   Fruit       2018-03    0
3       Pizza   Fast Food   2018-01    2
4       Pizza   Fast Food   2018-02    1
5       Pizza   Fast Food   2018-03    3
6       Cake    Desert      2018-01    3
7       Cake    Desert      2018-02    6
8       Cake    Desert      2018-03    7

The ordering of the target DataFrame is not important.

like image 598
velxundussa Avatar asked Mar 05 '23 06:03

velxundussa


1 Answers

This is a typical wide_to_long question

pd.wide_to_long(df,'Eaten ',i=['Food','Type'],j='Month').reset_index()
Out[38]: 
    Food       Type    Month  Eaten 
0  Apple      Fruit  2018-01       3
1  Apple      Fruit  2018-02       4
2  Apple      Fruit  2018-03       0
3  Pizza  Fast Food  2018-01       2
4  Pizza  Fast Food  2018-02       1
5  Pizza  Fast Food  2018-03       3
6   Cake     Desert  2018-01       3
7   Cake     Desert  2018-02       6
8   Cake     Desert  2018-03       7
like image 150
BENY Avatar answered Mar 19 '23 02:03

BENY