Pandas: 考虑多个条件正确过滤 Dataframe 列

Pandas: Filter correctly Dataframe columns considering multiple conditions

我有一个代表餐厅顾客评分的数据框。 star_rating 是客户在此数据框中的评分。

data = {'rating_id': ['1', '2','3','4','5','6','7','8','9'],
        'user_id': ['56', '13','56','99','99','13','12','88','45'],
        'restaurant_id':  ['xxx', 'xxx','yyy','yyy','xxx','zzz','zzz','eee','eee'],
        'star_rating': ['2.3', '3.7','1.2','5.0','1.0','3.2','1.0','2.2','0.2'],
        'rating_year': ['2012','2012','2020','2001','2020','2015','2000','2003','2004'],
        'first_year': ['2012', '2012','2001','2001','2012','2000','2000','2001','2001'],
        'last_year': ['2020', '2020','2020','2020','2020','2015','2015','2020','2020'],
        'funny': ['1', '0','0','1','1','1','0','0','0'],
        'useful': ['1', '0','0','0','1','0','0','0','1'],
        'cool': ['1', '0','0','0','1','1','1','1','1'],

        }


df = pd.DataFrame (data, columns = ['rating_id','user_id','restaurant_id','star_rating','rating_year','first_year','last_year','funny','useful','cool'])
df['star_rating'] = df['star_rating'].astype(float)



filtered_data = df[(df['star_rating'] >= 3) & (df['funny']==1 | df['useful']==1 | df['cool']==1)]
d = filtered_data.groupby('restaurant_id')['star_rating'].count().to_dict()

df['nb_favorables_mention'] = df['restaurant_id'].map(d)
df.head(20)

我不确定我的语法有什么问题,但根据我的尝试,我不断收到这些错误消息

考虑到我要实现的目标,正确的语法是什么?

您遇到运算符优先级问题;在 python 中,| 运算符的优先级高于 ==,将比较表达式括在括号中应该可以解决您的问题,因为 funnyusefulcool列是str类型,使用string'1'代替number1:

filtered_data = df[(df['star_rating'] >= 3) & ((df['funny']=='1') | (df['useful']=='1') | (df['cool']=='1'))]

Check result here

除了使用|,你还可以一次性比较多个列,然后用any检查条件:

filtered_data = df[(df['star_rating'] >= 3) & df[['funny', 'useful', 'cool']].eq('1').any(axis=1)]