首页 > 解决方案 > 在 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...

只是对这里导致错误的原因感到迷茫。干杯。

标签: pythonpandasdataframefilter

解决方案


您可以执行以下操作来评论解决方案的替代方案:

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()

推荐阅读