gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:25 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com