+-----+-------+--------+
|     | Buyer |  Sex   |
+-----+-------+--------+
| 0   | 1     | Male   |
| 1   | 1     | Female |
| 2   | 0     | Male   |
| 3   | 1     | Female |
| ... | ...   | ...    |
+-----+-------+--------+


我想将上面的数据框求和并归入下面的数据框(表)。大熊猫有内置功能可以做到这一点吗?还是我必须手动进行迭代,求和和分组?

+---+---------+------+
|   | Female  | Male |
+---+---------+------+
| 0 |      81 |  392 |
| 1 |     539 |  233 |
+---+---------+------+

最佳答案

使用pivot_table,将'count'用作您的aggfunc。
另外,考虑到可能从未找到某些组合,请使用fillna用0填充空白单元格:

In [28]:
df['V'] = 1
print df
   Buyer     Sex  V
0      1    Male  1
1      1  Female  1
2      0    Male  1
3      1  Female  1
In [29]:
print df.pivot_table(index='Buyer', columns='Sex', values='V', aggfunc='count').fillna(0)
Sex    Female  Male
Buyer
0           0     1
1           2     1

关于python - 如何对数据框元素进行汇总和分组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33921986/

10-14 01:26