要将多列合并为一列并计算唯一值的重复,并为熊猫数据框中的每个计数维护一个单独的列

时间:2019-03-06 17:41:43

标签: python-3.x pandas

我有一个这样的Pandas数据框:

                Q1            Q2           Q3               Q4  
0               Bachelor    Postgrad    Postgrad        Masters     
1               Bachelor    Postgrad    Postgrad        Bachelor        
2               Masters     Postgrad    Postgrad        Masters     
3               Bachelor    Bachelor    Bachelor        Masters     
4               Bachelor    NaN NaN     Masters         Masters
...

我想添加这样的列:

        Q1          Q2         Q3           Q4     Bachelor  Masters  Postgrad 
0   Bachelor    Postgrad    Postgrad    Masters       1        1        2
1   Bachelor    Postgrad    Postgrad    Bachelor      2        0        2
2   Masters     Postgrad    Postgrad    Masters       0        2        2
3   Bachelor    Bachelor    Bachelor    Masters       3        1        0
4   Bachelor      NaN       Masters     Masters       1        1        1
...

我尝试过并且能够将Q1到Q4合并为一列,但是无法计算唯一值并将这些计数打印在单独的列中。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:2)

您正在寻找get_dummies

s=pd.get_dummies(df,prefix='', prefix_sep='').sum(1,level=0)
s
Out[502]: 
   Bachelor  Masters  Postgrad
0         1        1         2
1         2        0         2
2         0        2         2
3         3        1         0
4         1        2         0
# then using concat 
df=pd.concat([df,s],axis=1)