2013-09-27 54 views
3

我嘗試轉換這樣的列表的列表中創建一個數據幀:從長度不相等的列表

l = [[1, 2, 3, 17], [4, 19], [5]] 

到具有每個號碼作爲指數之和列表作爲值的位置的數據幀。

例如,19在第二個列表中,因此我期望得到somwhere一行,「19」作爲索引,「1」作爲值,依此類推。

我設法得到它(以下cf.boiler板),但我想有一些更簡單的

>>> df=pd.DataFrame(l)  
>>> df=df.unstack().reset_index(level=0,drop=True)  
>>> df=df[df.notnull()==True] # remove NaN rows 
>>> df=pd.DataFrame(df)  
>>> df = df.reset_index().set_index(0)  
>>> print df 
    index 
0   
1  0 
4  1 
5  2 
2  0 
19  1 
3  0 
17  0 

在此先感謝。

回答

3
In [52]: pd.DataFrame([(item, i) for i, seq in enumerate(l) 
         for item in seq]).set_index(0) 
Out[52]: 
    1 
0  
1 0 
2 0 
3 0 
17 0 
4 1 
19 1 
5 2