python-3.x - 将多列合并为一列并计算唯一值的重复次数,并为 Pandas 数据框中的每个计数维护一个单独的列

标签 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 合并到一列中,但无法计算唯一值并将这些计数打印在单独的列中。对此的任何帮助将不胜感激。

最佳答案

您正在寻找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/

相关文章:

python - Pylint 给我 "Final new line missing"

python - 从一个数据帧到另一个数据帧查找缺失值的正确方法

python - 在另一个单元格中的plot()之后未渲染AxesSubplot

python - 使用 pandas 旋转多个列

python - 比较两个电子表格并提取值

python - Pandas数据框如何按值分组,按降序值排序,然后过滤到分位数(0.1)

python-3.x - Simplejson 错误 Python 3.3

python - 如何创建嵌套字典,以便通过Python为Elasticsearch创建映射?

python - 并发任务确定性地生成伪随机数

python - 什么可能导致此错误: FileNotFoundError: [Errno 2] No such file or directory