2016-11-02 84 views
1

如何将列表分解成行?将多列列表分解成行

,我有以下的数据帧:

df = pd.DataFrame([(1,[1,2,3],['a','b','c']),(2,[4,5,6],['d','e','f']),(3,[7,8],['g','h'])]) 

我想有以下输出:

0 1 2 
0 1 1 a 
1 1 2 b 
2 1 3 c 
3 2 4 d 
4 2 5 e 
5 2 6 f 
6 3 7 g 
7 3 8 h 

回答

2

可以使用str.lenlists GET长度由numpy.repeatflattening lists重复:

from itertools import chain 
import numpy as np 

df2 = pd.DataFrame({ 
     0: np.repeat(df.iloc[:,0].values, df.iloc[:,1].str.len()), 
     1: list(chain.from_iterable(df.iloc[:,1])), 
     2: list(chain.from_iterable(df.iloc[:,2]))}) 

print (df2)   
    0 1 2 
0 1 1 a 
1 1 2 b 
2 1 3 c 
3 2 4 d 
4 2 5 e 
5 2 6 f 
6 3 7 g 
7 3 8 h 
+0

它是如何工作的? – jezrael