Home > front end >  Pandas Reshape dataframe without using melt function
Pandas Reshape dataframe without using melt function

Time:01-05

I have a dataframe as : dataframe

i need to convert it as final result like this df after reshape

I need the rows name and id with value 1 as according on last 3 columns as shown in the image. It can be done using pandas melt function but i was looking forward to do without using the library.

How can it be done??

CodePudding user response:

melt is designed for these operations, but an alternative would be to set your index on id and name, using set_index(), and use stack:

df.set_index(['id','name']).stack()\
                           .reset_index(name='val')\
                           .query('val == 1')\
                           .rename({'level_2':'language'},axis=1)\
                           .drop('val',axis=1)

prints:

   id    name language
0   1    Alex   python
1   1    Alex     java
2   1    Alex    mysql
3   2  Herald   python
5   2  Herald    mysql
6   3    Jack   python
9   4    Mike   python
  •  Tags:  
  • Related