我有一个像这样的 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 合并到一列中,但无法计算唯一值并将这些计数打印在单独的列中。对此的任何帮助将不胜感激。
最佳答案
您正在寻找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)
关于python-3.x - 将多列合并为一列并计算唯一值的重复次数,并为 Pandas 数据框中的每个计数维护一个单独的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55029189/