How to convert a column to rows in pandas?

I have a dataframe:

user_id    product_name
0001       a
0001       b
0001       c
0002       b
0003       a
0003       c
0003       d

I want the product_name column to convert to this:

user_id    A    B    C    D
0001       a    b    c    NaN
0002       NaN  b    NaN  NaN
0003       a    NaN  c    d
+4
source share
1 answer

First of all, we will create a duplicate column product_nameto name it product_name_extra, we will use this column later

df['product_name_extra'] = df.product_name
Out[223]:
user_id      product_name   product_name_extra
1                  a                a
1                  b                b
1                  c                c
2                  b                b
3                  a                a
3                  c                c
3                  d                d

then rotating the edited data frame check pivot if you want more information about the rotation

df_pivot = df.pivot(index='user_id' , columns='product_name' , values='product_name_extra')
Out[222]:
product_name    a   b   c   d
user_id             
1               a   b   c   NaN
2               NaN b   NaN NaN
3               a   NaN c   d

then finally rename the columns

df_pivot.rename(columns=str.upper)
Out[225]:
product_name    A   B   C   D
user_id             
1               a   b   c   NaN
2               NaN b   NaN NaN
3               a   NaN c   d
+4
source

Source: https://habr.com/ru/post/1607420/


All Articles