pandas :将列中的列表分成多行 [英] Pandas: split list in column into multiple rows

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

问题描述

我有一个关于将数据框列中的列表分成多行的问题.

I have a question regarding splitting a list in a dataframe column into multiple rows.

假设我有这个数据框:

  Job position   Job type  id
0          [6]        [1]   3
1       [2, 6]  [3, 6, 5]   4
2          [1]        [9]  43

我想要数字的每一个组合,所以最终结果将是:

I would like every single combination of numbers, so the final result would be:

   id    Job position  Job type
0   3         6.0       1.0
1   4         2.0       3.0
2   4         2.0       6.0
3   4         2.0       5.0
4   4         6.0       3.0
5   4         6.0       6.0
6   4         6.0       5.0
7  43         1.0       9.0

因为现在我得到了这个结果:

Because right now I get this result:

   id    Job position  Job type
0   3         6.0       1.0
1   4         2.0       3.0
2   4         6.0       6.0
3   4         NaN       5.0
4  43         1.0       9.0

为了得到上面的结果,我做了:

In order to get the result above, I did:

df = df.set_index(['id'])
(df.apply(lambda x: pd.DataFrame(x.tolist(),index=x.index)
                        .stack()
                        .rename(x.name)).reset_index())

推荐答案

类似于Scott Boston的建议,我建议您分别展开各列,然后将它们合并在一起.

Similar to Scott Boston's suggestion, I suggest you explode the columns separately, then merge them together.

例如,对于职位":

>>> df['Job position'].apply(pd.Series).reset_index().melt(id_vars='index').dropna()[['index', 'value']].set_index('index')
    value
index   
0   6.0
1   2.0
2   1.0
1   6.0

而且,一起:

df = pd.DataFrame({'Job position': [[6], [2, 6], [1]], 'Job type': [[1], [3, 6, 5], [9]], 'id': [3, 4, 43]})
jobs = df['Job position'].apply(pd.Series).reset_index().melt(id_vars='index').dropna()[['index', 'value']].set_index('index')
types = df['Job type'].apply(pd.Series).reset_index().melt(id_vars='index').dropna()[['index', 'value']].set_index('index')
>>> pd.merge(
    pd.merge(
        jobs,
        types,
        left_index=True,
        right_index=True),
    df[['id']],
    left_index=True,
    right_index=True).rename(columns={'value_x': 'Job positions', 'value_y': 'Job type'})
Job positions   Job type    id
0   6.0 1.0 3
1   2.0 3.0 4
1   2.0 6.0 4
1   2.0 5.0 4
1   6.0 3.0 4
1   6.0 6.0 4
1   6.0 5.0 4
2   1.0 9.0 43

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

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