2016-11-07 52 views
2

我有一个表格,其中一列是二进制功能的数组,他们在那里时,该功能是存在的。将一列中的Array值转换为原始DataFrame的列的最佳方式是什么?

我想在这些行上训练逻辑模型,但无法获取所需格式的数据,其中每个要素值都是自己的具有1或0值的列。

例子:

id feature values 
1  ['HasPaws', 'DoesBark', 'CanFetch'] 
2  ['HasPaws', 'CanClimb', 'DoesMeow'] 

我希望得到它的

id HasPaws DoesBark CanFetch CanClimb DoesMeow 
1  1   1   1   0   0 
2  1   0   0   1   0 

好像有将建在完成此部分功能的格式,但我不能想想这种转变被称为是为了更好地搜索自己。

回答

4

你可以先转换列表的列,然后使用get_dummies()方法:

In [12]: df 
Out[12]: 
    id     feature_values 
0 1 [HasPaws, DoesBark, CanFetch] 
1 2 [HasPaws, CanClimb, DoesMeow] 

In [13]: (pd.get_dummies(df.set_index('id').feature_values.apply(pd.Series), 
    ...:     prefix='', prefix_sep='') 
    ...: .reset_index() 
    ...:) 
Out[13]: 
    id HasPaws CanClimb DoesBark CanFetch DoesMeow 
0 1  1   0   1   1   0 
1 2  1   1   0   0   1 
3

另一种选择是遍历feature values柱,构建从在列表中的索引值每一个小区的系列。并以这种方式,熊猫将扩大串联成的数据帧与index作为标头:

pd.concat([df['id'], 
      (df['feature values'].apply(lambda lst: pd.Series([1]*len(lst), index=lst)) 
      .fillna(0)], axis=1) 

enter image description here

2

方法1

pd.concat([df['id'], df['feature values'].apply(pd.value_counts)], axis=1).fillna(0) 

方法2

df.set_index('id').squeeze().apply(pd.value_counts).reset_index().fillna(0) 

方法3

pd.concat([pd.Series(1, f, name=i) for _, (i, f) in df.iterrows()], 
      axis=1).T.fillna(0).rename_axis('id').reset_index() 

enter image description here

相关问题