python - 在 python 中的数据帧上使用 group by 后,如何过滤数据帧以返回特定类型的记录?
问题描述
昨晚带着一个关于group by的问题来到这里,并找到了一个非常快速的解决方案!我现在正在尝试解决一个问题,尽管我可以返回一个数据框,其中只有一个我在我的 df 中拥有的多个“complaint_type”,但是,我的 df 按“complaint_type”分组
我试过只使用普通的过滤器语句,但是它说我有一个关键错误。下面显示了我的 df 以及我使用的语句。
# Original Data Frame
NY311_df
# Creating a new df from the original based on group by
b_ct_df = NY311_df.groupby(['borough','complaint_type']).count()
#Trying to return the same df, but only where the complaint type is
#'HEAT/HOT WATER'
b_ct_df[b_ct_df['complaint_type']=='HEAT/HOT WATER']
#The line above returns the error 'complaint_type' KeyError
我想返回每个行政区的“热水/热水”的投诉类型。我希望它看起来像这样 Bronx:Heat/Hot Water: 456, Brooklyn:Heat/Hot Water: 543, etc...
只是对这里导致错误的原因感到迷茫。干杯。
解决方案
您可以执行以下操作来评论解决方案的替代方案:
b_ct_df = NY311_df.groupby(['borough','complaint_type']).count().reset_index()
b_ct_df[b_ct_df['complaint_type']=='HEAT/HOT WATER']
或者你可以这样做:
b_ct_df = NY311_df[NY311_df['complaint_type']=='HEAT/HOT WATER'].groupby(['borough','complaint_type']).count()
推荐阅读
- java - 带有服务器端输入的 Java Linux 守护进程/服务
- reactjs - 为什么道具不更新?
- regex - 如何使用正则表达式查找字符串的一部分?
- javascript - 如何在 jQuery 中仅定位当前悬停的元素
- opc-ua - 如何将客户端身份链接到 OPC-UA 中的 userRole
- sql - 基于查询结果的自定义验证规则
- redis - redis:内存有限时删除最旧的键
- postgresql - 安装 kong-ingress-controller 来管理 kubernetes 上的入口
- svn - 在 Assembla - SVN 中,只有管理员可以创建新的存储库吗?
- c++ - 创建和调用空函数