gpt4 book ai didi

python - Pandas 从列中可用的列表数据中扩展行

转载 作者:太空狗 更新时间:2023-10-29 16:54:45 25 4
gpt4 key购买 nike

我在 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为此的方法,它将列表扩展为每个元素的一行并重复其余列:

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 链接:

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

关于python - Pandas 从列中可用的列表数据中扩展行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39011511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com