2016-07-27 187 views
2

什麼是更可伸縮的方式從項目集列表::蟒蛇大熊貓數據幀

itemset = [['a', 'b'], 
      ['b', 'c', 'd'], 
      ['a', 'c', 'd', 'e'], 
      ['d'], 
      ['a', 'b', 'c'], 
      ['a', 'b', 'c', 'd']] 

去這種::

>>> df 
    a b c d e 
0 1 1 0 0 0 
1 0 1 1 1 0 
2 1 0 1 1 1 
3 0 0 0 1 0 
4 1 1 1 0 0 
5 1 1 1 1 0 
>>> 

DF的目標大小的數據幀是1e6行和500列。

+0

對稱問題是http://stackoverflow.com/q/38605111/3313834 – user3313834

回答

0

這裏是一個幾乎量化的方法 -

items = np.concatenate(itemset)   
col_idx = np.fromstring(items, dtype=np.uint8)-97 

lens = np.array([len(item) for item in itemset]) 
row_idx = np.repeat(np.arange(lens.size),lens) 
out = np.zeros((lens.size,lens.max()+1),dtype=int) 
out[row_idx,col_idx] = 1 

df = pd.DataFrame(out,columns=np.unique(items)) 

最後一行可以用的東西來替代這樣的,可能是更好的性能 -

df = pd.DataFrame(out,columns=items[np.unique(col_idx,return_index=True)[1]]) 
2

您可以使用get_dummies

print (pd.DataFrame(itemset)) 
    0  1  2  3 
0 a  b None None 
1 b  c  d None 
2 a  c  d  e 
3 d None None None 
4 a  b  c None 
5 a  b  c  d 
df1 = (pd.get_dummies(pd.DataFrame(itemset), prefix='', prefix_sep='')) 
print (df1) 
    a b d b c c d d e 
0 1.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 
1 0.0 1.0 0.0 0.0 1.0 0.0 1.0 0.0 0.0 
2 1.0 0.0 0.0 0.0 1.0 0.0 1.0 0.0 1.0 
3 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 
4 1.0 0.0 0.0 1.0 0.0 1.0 0.0 0.0 0.0 
5 1.0 0.0 0.0 1.0 0.0 1.0 0.0 1.0 0.0 

print (df1.groupby(df1.columns, axis=1).sum().astype(int)) 
    a b c d e 
0 1 1 0 0 0 
1 0 1 1 1 0 
2 1 0 1 1 1 
3 0 0 0 1 0 
4 1 1 1 0 0 
5 1 1 1 1 0