gpt4 book ai didi

python - 在python中分解多个csv字段

转载 作者:行者123 更新时间:2023-11-28 21:05:18 25 4
gpt4 key购买 nike

我有一个包含 200 行的 excel 文件,其中 2 行以逗号分隔值。如果我将它们输出为制表符分隔,它将如下所示:

col1  col2    col3
a b,c d,e
f g,h i,j

我需要分解才能得到这样的数据框,将 200 行分解为 ~4,000 行:

col1  col2  col3
a b d
a b e
a c d
a c e
f g i
f g j
f h i
f h j

我在 pandas 中没有看到任何爆炸功能,并且无法弄清楚如何在逗号分隔值的列长度不均匀的情况下执行此操作 - 不确定拆分在这里如何工作。

帮助我堆栈溢出,你是我唯一的希望。谢谢!

最佳答案

使用itertools.product获取col2和col3之间的所有组合,然后将它们转换成单独的列

from itertools import product
df.set_index('col1')\
.apply(lambda x: pd.Series(list(product(x.col2.split(','),x.col3.split(',')))),axis=1)\
.stack()\
.reset_index(1,drop=True)\
.apply(pd.Series)\
.reset_index().rename(columns={0:'col1',1:'col3'})

Out[466]:
col1 col1 col3
0 a b d
1 a b e
2 a c d
3 a c e
4 f g i
5 f g j
6 f h i
7 f h j

关于python - 在python中分解多个csv字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44361394/

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