简体   繁体   English

如何在条件下对熊猫数据框进行子集

[英]how to subset pandas dataframe on a condition

I have a pandas dataframe like this: 我有一个这样的熊猫数据框:

 buyer_id meal_type
    139       Veg
    140    NonVeg
    140       Veg
     36    NonVeg
     79       Veg
     79    NonVeg
     79    NonVeg
     72    NonVeg
     72    NonVeg
     65    NonVeg
     65       Veg

Now I want all the buyer_id which has only Veg as a meal type,all the buyer_id which has Veg and NonVeg as meal type and all the buyer_id which has only NonVeg as a meal type. 现在,我希望所有的buyer_id它只有Veg作为一餐类型,所有的buyer_id其中有Veg and NonVeg作为膳食类型和所有buyer_id它只有NonVeg作为膳食类型。

so, 所以,

139 Veg
140 Veg and NonVeg
36  NonVeg
79  Veg and NonVeg

and so on. 等等。 I am doing the following in Python to get all the buyer ids that have Veg , NonVeg or both. 我正在Python中执行以下操作,以获取具有VegNonVeg或两者都有的所有买方ID。

segments_data.buyer_id[segments_data['meal_type']=='Veg' &      
segments_data['meal_type']=='NonVeg']

But It doesn't work. 但这行不通。 Please help. 请帮忙。

Grouping by buyer_id and converting meal_type into a set works: 通过分组buyer_id和转换meal_type成一组作品:

>>> df.groupby('buyer_id')['meal_type'].apply(set).str.join(' and ')

    buyer_id
36             NonVeg
65     Veg and NonVeg
72             NonVeg
79     Veg and NonVeg
139               Veg
140    Veg and NonVeg
Name: meal_type, dtype: object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM