我有一个Python Pandas DataFrame,如下所示:
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
也有兴趣以不同的方式创建这种类型的二进制矩阵!
感谢任何帮助!
由于
答案 0 :(得分:5)
我认为你可以使用:
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
答案 1 :(得分:0)
我写了一个支持分组的通用函数,暂时这样做:
ComputerOrder order = new ComputerOrder<Peripheral>();
// Add peripherals, printers,...
// Apples, motherboards (ComputerProduct, but NOT Peripheral) will fail...
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