DataFrame中weight_class过滤规则不生效问题求助
解决Pandas中Rice的weight_class过滤规则不生效的问题
你的问题出在过滤逻辑的逻辑运算符使用错误:
- 你定义的
grocery_basket里已经包含了'Rice',所以df['product'].isin(grocery_basket)这一条件会直接把所有product为Rice的条目(不管weight_class是10917还是10924)都筛选出来。 - 后面的
((df['product'] == 'Rice') & (df['weight_class'] != 10917))因为用了|(逻辑或),完全被前面的条件覆盖,根本不会生效。
修正方案
方案一:调整过滤逻辑,拆分商品列表和Rice的条件
把grocery_basket里的'Rice'移除,然后用逻辑或组合「其他指定商品」和「符合weight_class要求的Rice」:
# Fill missing values with zeros in the original DataFrame df.fillna(0, inplace=True) df['weight_class'] = df['weight_class'].astype(int) # 移除列表中的Rice,单独处理 grocery_basket = ['Loaf of white bread', 'Sunflower oil', 'Maize meal', 'White sugar', 'Full cream milk - fresh', 'Cake flour', 'Bar Of Bath Soap', 'Spaghetti', 'Peanut butter', 'Cereals', 'Rooibos tea'] # 过滤逻辑:其他指定商品 或者 符合weight_class的Rice selected_items = df[(df['product'].isin(grocery_basket)) | ((df['product'] == 'Rice') & (df['weight_class'] == 10924))] print(selected_items)
方案二:保留原商品列表,添加Rice的额外过滤条件
如果不想修改grocery_basket,可以用逻辑与组合「属于指定商品列表」和「如果是Rice则weight_class符合要求」:
# Fill missing values with zeros in the original DataFrame df.fillna(0, inplace=True) df['weight_class'] = df['weight_class'].astype(int) # Define the grocery basket grocery_basket = ['Loaf of white bread', 'Sunflower oil', 'Maize meal', 'White sugar', 'Full cream milk - fresh', 'Rice', 'Cake flour', 'Bar Of Bath Soap', 'Spaghetti', 'Peanut butter', 'Cereals', 'Rooibos tea'] # 过滤逻辑:属于指定列表,并且(不是Rice 或者 是Rice且weight_class为10924) selected_items = df[df['product'].isin(grocery_basket) & ((df['product'] != 'Rice') | (df['weight_class'] == 10924))] print(selected_items)
额外验证步骤
如果修正后还是有问题,可以先确认数据是否符合预期:
- 检查
weight_class列的实际值:print(df[df['product'] == 'Rice']['weight_class'].unique()),确认只有10917和10924两种值 - 确认类型转换成功:
print(df['weight_class'].dtype),确保是int64
内容的提问来源于stack exchange,提问作者Kyle Ebrahim
相关产品推荐
相关产品推荐

