大熊猫:考虑多种情​​况正确过滤数据框列

时间:2020-09-26 20:12:03

标签: python pandas dataframe jupyter-notebook feature-engineering

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

  • 我想做的是在同一数据框中添加一列nb_favorables_mention,该列表示获得至少一项“有用”,“有趣”或“酷”评级的评论总数并且评论的评分为> = 3。
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)

我不确定语法有什么问题,但是从我尝试过的过程中,我不断收到这些错误消息

  • ValueError:系列的真值不明确。使用a.empty,a.bool(),a.item(),a.any()或a.all()。

  • TypeError:无法对类型为[bool]的标量[object]数组和标量执行'ror _'

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

1 个答案:

答案 0 :(得分:2)

您有一个运算符优先级问题;在python中,|运算符的优先级比==高,用括号括起比较表达式应该可以解决您的问题,因为funnyusefulcool列是str类型,使用字符串'1'而不是数字1

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