在python中分解多个csv字段

2024-04-20 09:52:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个excel文件,有200行,其中2行有逗号分隔的值。如果我将它们输出到tab separated,它将如下所示:

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

我需要分解得到这样的数据帧,将200行分解成4000行:

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中看不到任何分解功能,也不知道如何在逗号分隔的列长度不均匀的情况下实现这一点-不知道split在这里如何工作。你知道吗

帮我,你是我唯一的希望。谢谢!你知道吗


Tags: 文件数据功能pandas情况exceltabcol2
1条回答
网友
1楼 · 发布于 2024-04-20 09:52:54

使用itertools.产品获取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

相关问题 更多 >