Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dataframe exploded list column into multiple rows [duplicate]

I have a dataframe like this:

         desc     id     info  
       [a,b,c]     2     type
       [u,v,w]     18    tail

Three columns: desc,id,info and desc is a list.I want this:

        des    id    info 
         a      2     type
         b      2     type
         c      2     type 
         u      18    tail
         v      18    tail
         w      18    tail

That means exploded the list column into multiple rows and other column no changes. I really don't know how to do this...

like image 530
宋国庆 Avatar asked Dec 22 '25 14:12

宋国庆


1 Answers

Here is one way

df.set_index(['id', 'info']).desc.apply(pd.Series).stack()\
.reset_index(name = 'desc').drop('level_2', axis = 1)


    id  info    desc
0   2   type    a
1   2   type    b
2   2   type    c
3   18  tail    u
4   18  tail    v
5   18  tail    w
like image 177
Vaishali Avatar answered Dec 24 '25 04:12

Vaishali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!