将类别作为值转换为DataFrame掩码的pandas Series

时间:2017-08-17 13:02:26

标签: python pandas numpy dataframe

我有一个非常简单的问题,我不确定如何通过一些简单的调用来解决。我有以下系列:

In [3]: d = pd.Series(data=['A', 'A', 'B', 'C', 'D', 'D', 'B'], index=range(7))

In [4]: d
Out[4]: 
0    A
1    A
2    B
3    C
4    D
5    D
6    B
dtype: object

我希望将上述内容转换为:

In [5]: pd.DataFrame({'A':[1, 1, 0, 0, 0, 0, 0], 'B': [0, 0, 1, 0, 0, 0, 1], 'C':[0, 0, 0, 1, 0, 0, 0], 'D':[0, 0, 0, 0, 1, 1, 0]})
Out[5]: 
   A  B  C  D
0  1  0  0  0
1  1  0  0  0
2  0  1  0  0
3  0  0  1  0
4  0  0  0  1
5  0  0  0  1
6  0  1  0  0

简而言之,让系列具有重复值。我想创建一个与Series相同索引的DataFrame,而列是该系列的唯一值集。然后我想填充每一列,在列的每个索引处放置1,其中列名存在于其他地方。不知道如何以简单的方式做到这一点。

2 个答案:

答案 0 :(得分:4)

我们可以使用Series.str.get_dummies

In [308]: d.str.get_dummies()
Out[308]:
   A  B  C  D
0  1  0  0  0
1  1  0  0  0
2  0  1  0  0
3  0  0  1  0
4  0  0  0  1
5  0  0  0  1
6  0  1  0  0

或者我们可以使用sklearn.preprocessing.LabelBinarizer

In [321]: from sklearn.preprocessing import LabelBinarizer

In [322]: lb = LabelBinarizer()

In [323]: pd.DataFrame(lb.fit_transform(d), columns=lb.classes_, index=d.index)
Out[323]:
   A  B  C  D
0  1  0  0  0
1  1  0  0  0
2  0  1  0  0
3  0  0  1  0
4  0  0  0  1
5  0  0  0  1
6  0  1  0  0

答案 1 :(得分:3)

使用pd.get_dummies

In [419]: pd.get_dummies(d).astype(int)
Out[419]: 
   A  B  C  D
0  1  0  0  0
1  1  0  0  0
2  0  1  0  0
3  0  0  1  0
4  0  0  0  1
5  0  0  0  1
6  0  1  0  0

其他答案中的(稍微)较短的版本也可以。