How to use df.pivot in Pandas

df.pivot method in Pandas spreads rows into columns, df.pivot uses unique values from from specified columns to form axes of the resulting DataFrame. Below code snippet shows how to use df.pivot in pandas.

Create Dataframe


import pandas as pd

df = pd.DataFrame({'col1': ['test1', 'test2', 'test1', 'test2', 'test1','test2'],
                   'col2': ['aa', 'bb', 'cc', 'ee', 'gg', 'kk'],
                   'col3': [11, 23, 34, 46, 56, 66],
                   'col4': ['rx', 'ry', 'yz', 'qu', 'gw', 'rt']})

print(df)

Output:


    col1 col2  col3 col4
0  test1   aa    11   rx
1  test2   bb    23   ry
2  test1   cc    34   yz
3  test2   ee    46   qu
4  test1   gg    56   gw
5  test2   kk    66   rt

Applying df.pivot on Dataframe


df2 = df.pivot(columns="col1", values=["col2", "col3"])

print(df2)

In the above code columns="col1", specify values of "col1" to use as new frames columns and values=["col2", "col3"] specifies columns used for populating values in new frame.

Output:


      col2        col3
col1 test1 test2 test1 test2
0       aa   NaN    11   NaN
1      NaN    bb   NaN    23
2       cc   NaN    34   NaN
3      NaN    ee   NaN    46
4       gg   NaN    56   NaN
5      NaN    kk   NaN    66

Follow US on Twitter: