Skip to content
Advertisement

How to transform such a long to wide table?

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
...

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement