Python数据框将列表列分解为多行 [英] Python dataframe exploded list column into multiple rows

查看:366
本文介绍了Python数据框将列表列分解为多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框:

I have a dataframe like this:

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

三列:desc,id,info和desc是一个列表.我想要这个:

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

推荐答案

这是一种方法

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

这篇关于Python数据框将列表列分解为多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆