2017-06-05 93 views
2

我有一个200行的excel文件,其中2个文件中有逗号分隔的值。如果我把它们输出到制表符分隔的,它应该是这样的:在python中爆炸多个csv字段

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 

我不没有看到熊猫中的任何爆炸功能,也无法弄清楚如何做到这一点,因为逗号分隔值的列长度不均匀 - 不知道如何拆分在这里工作。

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

回答

5

使用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 
+0

尼斯阿伦.... +1 –

+0

感谢@ScottBoston – Allen

+0

我不会去被解雇了!哈哈。在我的数据上工作就像一个魅力。谢谢你,@allen&Scott非常感谢!我需要用大熊猫变得更好,并检查itertools。非常感激。 –