Python数据帧将列表列分解为多行

2024-04-25 07:46:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据帧:

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

三列:desc、id、info和desc是一个列表。我想要这个:

^{pr2}$

这意味着将列表列分解为多行,而其他列没有更改。 我真的不知道怎么做。。。在


Tags: 数据infoid列表typedesctailpr2
3条回答

有一种方法

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

我记得这应该是来自piRSquared或cᴏʟᴅsᴘᴇᴅ,但找不到链接。。。在

idx = np.arange(len(df)).repeat(df.desc.str.len(), 0)
out = df.iloc[idx, ].assign(desc=np.concatenate(df.desc.values))
out
Out[100]: 
  desc  id  info
0    a   2  type
0    b   2  type
0    c   2  type
1    u  18  tail
1    v  18  tail
1    w  18  tail

您可以展平desc列,repeat其他两列,然后将它们连接起来:

pd.concat([
    pd.Series([e for s in df.desc for e in s], name='desc'),
    df.drop('desc', 1).apply(lambda col: col.repeat(df.desc.str.len())).reset_index(drop=True)
], axis=1)

#desc   id  info
#0  a    2  type
#1  b    2  type
#2  c    2  type
#3  u   18  tail
#4  v   18  tail
#5  w   18  tail

相关问题 更多 >