2016-04-07 132 views
1

我有一個Python熊貓數據框類似如下:Python熊貓:如何從列的列創建二進制矩陣?

 1 
0 a, b 
1  c 
2  d 
3  e 

a, b爲代表的用戶列表的字符串特徵

我怎麼能轉換成用戶的功能,如下面的二元矩陣這樣的:

 a b c d e 
0 1 1 0 0 0 
1 0 0 1 0 0 
2 0 0 0 1 0 
3 0 0 0 0 1 

我看到了類似的問題,但Creating boolean matrix from one column with pandas列不包含在列表中的條目。

我曾嘗試這些方法,有沒有辦法合併兩個:

pd.get_dummies()

pd.get_dummies(df[1]) 


    a, b c d e 
0  1 0 0 0 
1  0 1 0 0 
2  0 0 1 0 
3  0 0 0 1 

df[1].apply(lambda x: pd.Series(x.split()))

 1 
0 a, b 
1  c 
2  d 
3  e 

也有興趣在不同的方法來創建這種類型的二元矩陣!

任何幫助表示讚賞!

感謝

回答

3

我認爲你可以使用:

df = df.iloc[:,0].str.split(', ', expand=True) 
     .stack() 
     .reset_index(drop=True) 
     .str.get_dummies() 

print df 
    a b c d e 
0 1 0 0 0 0 
1 0 1 0 0 0 
2 0 0 1 0 0 
3 0 0 0 1 0 
4 0 0 0 0 1 

編輯:

print df.iloc[:,0].str.replace(' ','').str.get_dummies(sep=',') 
    a b c d e 
0 1 1 0 0 0 
1 0 0 1 0 0 
2 0 0 0 1 0 
3 0 0 0 0 1 
+0

有沒有必要鏈,使許多操作在一起只是爲了讓一個班輪.. – DSM

+0

@jezrael這工作了魅力,非常感謝! – jfive

+0

有趣的是,對'10,000'行工作,但iPython內核死在'100,000'行上,將嘗試以10,000和垂直連接的塊進行計算。 – jfive

0

我寫了一個通用的函數,與分組的支持,要做到這一點而回:

def sublist_uniques(data,sublist): 
    categories = set() 
    for d,t in data.iterrows(): 
     try: 
      for j in t[sublist]: 
       categories.add(j) 
     except: 
      pass 
    return list(categories) 

def sublists_to_dummies(f,sublist,index_key = None): 
    categories = sublist_uniques(f,sublist) 
    frame = pd.DataFrame(columns=categories) 
    for d,i in f.iterrows(): 
     if type(i[sublist]) == list or np.array: 
      try: 
       if index_key != None: 
        key = i[index_key] 
        f =np.zeros(len(categories)) 
        for j in i[sublist]: 
         f[categories.index(j)] = 1 
        if key in frame.index: 
         for j in i[sublist]: 
          frame.loc[key][j]+=1 
        else: 
         frame.loc[key]=f 
       else: 
        f =np.zeros(len(categories)) 
        for j in i[sublist]: 
         f[categories.index(j)] = 1 
        frame.loc[d]=f 
      except: 
       pass 

    return frame 
In [15]: a 
Out[15]: 
    a group  labels 
0 1 new  [a, d] 
1 2 old [a, g, h] 
2 3 new [i, m, a] 

In [16]: sublists_to_dummies(a,'labels') 
Out[16]: 
    a d g i h m 
0 1 1 0 0 0 0 
1 1 0 1 0 1 0 
2 1 0 0 1 0 1 

In [17]: sublists_to_dummies(a,'labels','group') 
Out[17]: 
    a d g i h m 
new 2 1 0 1 0 1 
old 1 0 1 0 1 0