Search code examples
pandasdataframerowstranspose

How to transpose every n rows in a data frame including two columns and show them as column using pandas


I've a pandas data frame which in its first column, the values are repeating every 5 rows like this:

ITEM    VALUE
=====   ======
item1   value1
item2   value2
item3   value3
item4   value4
item5   value5
item1   value6
item2   value7
item3   value8
item4   value9
item5   value10

i need to make a data frame like below with unique values from column 1 to use it as header and transpose every 5 records from column 2 under it. any easy way to do this using pandas? i checked all the pages in stackoverflow for data transposing using pandas but non of them was useful for this propose.

item1   item2   item3   item4   item5
======  ======  ======  ======  ======
value1  value2  value3  value4  value5
value6  value7  value8  value9  value10

Solution

  • Assign a group number and then pivot it:

    print (df.assign(group=df.index//5).pivot(index="group", values="VALUE", columns="ITEM"))
    
    ITEM    item1   item2   item3   item4    item5
    group                                         
    0      value1  value2  value3  value4   value5
    1      value6  value7  value8  value9  value10