Pandas 从列中可用的列表数据中扩展行 [英] Pandas expand rows from list data available in column
本文介绍了Pandas 从列中可用的列表数据中扩展行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Pandas 中有一个这样的数据框:
I have a data frame like this in pandas:
column1 column2
[a,b,c] 1
[d,e,f] 2
[g,h,i] 3
预期输出:
column1 column2
a 1
b 1
c 1
d 2
e 2
f 2
g 3
h 3
i 3
如何处理这些数据?
推荐答案
DataFrame.explode
由于 pandas >= 0.25.0
我们有 explode
方法,它将列表扩展为一行每个元素并重复其余的列:
DataFrame.explode
Since pandas >= 0.25.0
we have the explode
method for this, which expands a list to a row for each element and repeats the rest of the columns:
df.explode('column1').reset_index(drop=True)
输出
column1 column2
0 a 1
1 b 1
2 c 1
3 d 2
4 e 2
5 f 2
6 g 3
7 h 3
8 i 3
由于 pandas >= 1.1.0
我们有 ignore_index
参数,所以我们不必与 reset_index
链接:
Since pandas >= 1.1.0
we have the ignore_index
argument, so we don't have to chain with reset_index
:
df.explode('column1', ignore_index=True)
输出
column1 column2
0 a 1
1 b 1
2 c 1
3 d 2
4 e 2
5 f 2
6 g 3
7 h 3
8 i 3
这篇关于Pandas 从列中可用的列表数据中扩展行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文