Python pandas:根据现有的列值添加新列,并将新列的值设置为1或0

时间:2017-06-08 08:19:53

标签: python python-2.7 pandas dataframe

我有一个名为df的数据框如下:

ticker        class_n  
  1              a
  2              b
  3              c
  4              d
  5              e
  6              f
  7              a
  8              b
  ............................

我想在此数据框中添加新列,新列名称是class_n的唯一类别的值(我的意思是不重复class_n)。此外,新列的值为1(如果class_n的值与列名相同),则其他为0。 例如,作为以下数据帧。我想得到如下新数据帧:

ticer  class_n   a     b    c   d   e    f   
  1       a      1     0    0   0   0    0
  2       b      0     1    0   0   0    0
  3       c      0     0    1   0   0    0
  4       d      0     0    0   1   0    0    
  5       e      0     0    0   0   1    0
  6       f      0     0    0   0   0    1
  7       a      1     0    0   0   0    0 
  8       b      0     1    0   0   0    0 

我的代码如下:

lst_class = list(set(list(df['class_n'])))
for cla in lst_class:
    df[c] = 0
    df.loc[df['class_n'] is cla, cla] =1 

但有错误:

KeyError: 'cannot use a single bool to index into setitem'

谢谢!

1 个答案:

答案 0 :(得分:2)

使用pd.get_dummies

df.join(pd.get_dummies(df.class_n))

   ticker class_n  a  b  c  d  e  f
0       1       a  1  0  0  0  0  0
1       2       b  0  1  0  0  0  0
2       3       c  0  0  1  0  0  0
3       4       d  0  0  0  1  0  0
4       5       e  0  0  0  0  1  0
5       6       f  0  0  0  0  0  1
6       7       a  1  0  0  0  0  0
7       8       b  0  1  0  0  0  0

或者同样的事情,但手动更多

f, u = pd.factorize(df.class_n.values)
d = pd.DataFrame(np.eye(u.size, dtype=int)[f], df.index, u)
df.join(d)

   ticker class_n  a  b  c  d  e  f
0       1       a  1  0  0  0  0  0
1       2       b  0  1  0  0  0  0
2       3       c  0  0  1  0  0  0
3       4       d  0  0  0  1  0  0
4       5       e  0  0  0  0  1  0
5       6       f  0  0  0  0  0  1
6       7       a  1  0  0  0  0  0
7       8       b  0  1  0  0  0  0