Python Pandas : How can I count the number of times a value appears in a column based upon another column?

标签 python pandas dataframe count

This is my pandas dataframe I am referring to.

基本上我希望能够显示 'crime type' 的计数基于'council' 。例如,其中 'council == Fermanagh and omagh'数数 每个 'crime type' 都有不同的值这有道理吗?所以burgulary可能等于 1而,Anti-social behaviour'将是3另一个'council' ?然后我想将这些值绘制在条形图上。

希望这是有道理的。任何帮助都会很棒。谢谢。

最佳答案

我相信你需要groupbysize :

df1 = df.groupby(['crime type', 'council']).size().reset_index(name='Count')

编辑:

df = pd.DataFrame({'crime type':['Anti-social behaviour','Anti-social behaviour',
                                 'Burglary','Burglary'],
                   'council':['Fermanagh and omagh','Belfast','Belfast','Belfast']})


df1 = df.groupby(['council', 'crime type']).size().unstack(fill_value=0)
print (df1)
crime type           Anti-social behaviour  Burglary
council                                             
Belfast                                  1         2
Fermanagh and omagh                      1         0

df1.plot.bar()

关于Python Pandas : How can I count the number of times a value appears in a column based upon another column?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47620346/

相关文章:

python - 如何在 DataFrame 上执行 concat 时分配默认值

python - Pandas:透视类型数据集

python - 检查一个 DataFrame 中的一行是否存在于另一个 DataFrame 中,仅基于特定的列

python - Pandas:使用重复值进行透视

python - 通过两列的并集重新索引 pandas 数据框

python - 在 python 中转换框架 pandas

Python:在没有目录的情况下将文件放入存档中?

java - 在这种情况下如何为hadoop编写partioner?

python - 使用wsgi在apache上部署flask app时如何解决权限错误?

python - 在球体表面上创建变形(使用Python?)