2017-06-05 39 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。非常感激。 –