如何提取熊猫系列元素并将其与数据帧列中的行进行比较



我有以下数据帧。。

     coupon_type     dish_id  dish_name   dish_price  dish_quantity
0     Rs 20 off       012      Sandwich     65            2
1     Rs 20 off       013       Chicken     125           3
2     Rs 20 off       013       Chicken     125           3
3     Rs 20 off       013       Chicken     125           3
    ratings    reviews      coupon_type  user_id order_id  meals order_area
    4     blah blah blah   Rs 20 off      9       9         5     London
    4     blah blah blah   Rs 20 off      9       9         5     London
    3     blah blah blah   Rs 20 off      9       9         5     London
    4     blah blah blah   Rs 20 off      9       9         5     London  

我在dish_name专栏上做groupby。

df_dish_name = df_final.groupby('dish_name')

然后我在groupby上执行一些比率运算。

这让我开始关注熊猫系列。。我存储在dish_specific_perf 中

dish_name
Chicken       45.000000
Sandwich      61.111111

然后我在if循环中检查一个条件。。

if((dish_specific_perf < 50).any() == True):

如果条件为true,那么我想在数据帧中的相应菜名中添加("NP")字符串。。所以,在数据帧中应该是这样的。

 coupon_type     dish_id  dish_name   dish_price  dish_quantity
0     Rs 20 off       012      Sandwich     65            2
1     Rs 20 off       013       Chicken     125           3
2     Rs 20 off       013       Chicken     125           3
3     Rs 20 off       013       Chicken     125           3
    ratings    reviews      coupon_type  user_id order_id  meals order_area
    4     blah blah blah   Rs 20 off      9       9         5     London
    4     blah blah blah   Rs 20 off      9       9         5     London
    3     blah blah blah   Rs 20 off      9       9         5     London
    4     blah blah blah   Rs 20 off      9       9         5     London  
  Flag
  Null
  NP
  NP
  NP

问题是如何将系列元素与dataframe dish_name列进行比较,以检查chicken是否存在?

当我做时

dish_specific_perf[0]  

它只给了我一个45的数字。

请帮忙。。

从本质上讲,您希望进行查找,我们可以在布尔序列上使用map,因此下面将添加布尔标志:

df_final['Flag'] = df_final['dish_name'].map(dish_specific_perf < 50)

这是通过对照序列索引查找df值并返回该值来实现的。

然后,您可以将布尔值转换为所需的标志:

df_final['Flag'] = np.where(df_final['Flag'], 'NP', 'Null')

首先,您的if语句不符合您的需求。我会在这样的小组中做整个循环:

for name, group in df_dish_name:
    # Whatever awesome thing you are doing, which give you the ratio...
    if ratio < 50:
        df_final.loc[df_final['dish_name']==name, 'Flag'] = 'NP'

这将避免多次索引和选择,并且更易于维护。

最新更新