Home > Software engineering >  How to transform such a long to wide table?
How to transform such a long to wide table?

Time:11-08

I am trying to transform this long dataframe to the wide dataframe with the following logic, the numbering of the columns is not important, what is important that the format stays this way as then I would need to use it for apriori algorithm.

      id     item
0     1     tea
1     2     butter
2     1     milk
3     3     apples
4     2     milk
5     6     wine
6.    6.    tea
...

      id     1         2         3         4         5 
0     1      tea      milk      NaN       NaN       NaN
1     2       NaN       NaN    butter     NaN       NaN
3     3       NaN       NaN      NaN      apples    NaN
5     6       tea       NaN      NaN      NaN      wine
...

CodePudding user response:

There are many different ways to reshape a pandas data frame from long to wide form. But the pivot_table() method is the most flexible and probably the only one you need to use once you learn it well.

You can use the syntax bellow, replacing the indexes, columns, and values with your data.

yourtable.pivot_table(index=["yourindex", "yourindex2"], 
                    columns='yourcollums', 
                    values='yourvalues')

This is a good tutorial that can help you learn more.

  • Related