python - 对 Python pandas 数据框中的唯一值进行分组和计数

标签 python pandas indexing dataframe

我有一个超过 33,000 行的数据框,我想对其进行简化:

                   Crime type
GeographyCode                              
E01006687          Burglary
E01007229          Anti-social behaviour
E01007229          Anti-social behaviour
E01007229          Anti-social behaviour
E01007229          Burglary
E01007229          Other theft
E01007229          Other theft
E01007229          Shoplifting
E01007229          Theft from the person
E01007230          Anti-social behaviour
E01007230          Anti-social behaviour
E01007230          Anti-social behaviour
E01007230          Anti-social behaviour
E01007230          Anti-social behaviour
E01007230          Anti-social behaviour
...

'GeographyCode' 有 207 个唯一值,'Crime type' 有 12 个唯一值。

我想制作一个新的数据框,它有 207 行和 12 列加上“GeographyCode”索引列,每列代表一种犯罪类型,并包含 GeographyCode 中该犯罪类型的所有发生次数。

像这样:

                Burglary   Anti-social    Theft   Shoplifting   etc...
GeographyCode
E01006687       1          3              9       5             ...
E01007229       1          3              2       1             ...
E01007230       0          6              12      5             ...
...

我已经尝试了一些方法,但是因为没有数值,我发现很难得到我需要的东西。

最佳答案

你可以使用 crosstab计算这个:

>>> pd.crosstab(df.index, df['Crime type'])
Crime type      Anti-social behaviour  Burglary  Other theft  Shoplifting  ...

E01006687                           0         1            0            0
E01007229                           3         1            2            1
E01007230                           6         0            0            0

关于python - 对 Python pandas 数据框中的唯一值进行分组和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33732697/

相关文章:

python - Python ""“""”中的多行f字符串将其他代码行转换为我要查找的字符串之外的字符串

python - 将有特殊要求的数据框写入csv文件

python - 将列添加到具有常量值的数据框中

python - 如何使用 Python 在 excel 文件中正确解析为由混合逗号和点分隔的文本数字?

mysql 无法添加外键 #1215

python - 文件读取在 Brython/Python 中不起作用

python - 忽略 Tensorflow 日志记录警告

python - 没有创建它应该创建的 csv 文件

PHP 数组索引错误

mysql - 如何让 mysql 通过简单的 AND + OR 查询使用索引?