pandas 爆炸多列 [英] Pandas explode multiple columns

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

问题描述

我有具有多列的 DF.其中两列是相同长度的列表.(col2 和 col3 是列表.列表的长度是相同的).

I have DF that has multiple columns. Two of the columns are list of the same len.( col2 and col3 are list. the len of the list is the same).

我的目标是在自己的行中列出每个元素.

My goal is to list each element on it's own row.

我可以使用df.explode().但它只接受一列.但是,我希望两列成对地爆炸".如果我执行 df.explode('col2')df.explode('col3'),它会得到 9 行而不是 3 行.

I can use the df.explode(). but it only accepts one column. However, I want the pair of the two columns to be 'exploded'. If I do df.explode('col2') and then df.explode('col3'), it results it 9 rows instead of 3.

原始 DF

col0      col1        col2        col3
1       aa          [1,2,3]     [1.1,2.2,3.3]
2       bb          [4,5,6]     [4.4,5.5,6.6]
3       cc          [7,8,9]     [7.7,8.8,9.9]
3       cc          [7,8,9]     [7.7,8.8,9.9]

结束数据帧

id      col1        col2        col3
1       aa          1           1.1
1       aa          2           2.2
1       aa          3           3.3
2       bb          4           4.4
2       bb          5           5.5
2       bb          6           6.6
3       cc          ...         ...

更新该列都没有唯一值,因此不能用作索引.

Update None of the column have unique values, so can't be used as index.

推荐答案

您可以将 col1 设置为索引并应用 pd.Series.explode 跨列:>

You could set col1 as index and apply pd.Series.explode across the columns:

df.set_index('col1').apply(pd.Series.explode).reset_index()

或者:

df.apply(pd.Series.explode)


   col1 col2 col3
0    aa    1  1.1
1    aa    2  2.2
2    aa    3  3.3
3    bb    4  4.4
4    bb    5  5.5
5    bb    6  6.6
6    cc    7  7.7
7    cc    8  8.8
8    cc    9  9.9
9    cc    7  7.7
10   cc    8  8.8
11   cc    9  9.9

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

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