我有一个超过 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/