使用 pandas 过滤多个值 [英] Filter Multiple Values using pandas

查看:55
本文介绍了使用 pandas 过滤多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python和Pandas.我有一个df,其工作原理与此类似:

I am using Python and Pandas. I have a df that works similar to this:

 +--------+--------+-------+
 |  Col1  |  Col2  | Col 3 |
 +--------+--------+-------+
 | Team 1 | High   | Pizza |
 | Team 1 | Medium | Sauce |
 | Team 1 | Low    | Crust |
 +--------+--------+-------+

我想过滤df,以便仅从Col2看到高"或中".

I would like to filter the df so that I only see High or Medium from Col2.

这是我没有运气尝试过的

This is what I have tried with no luck

 df = df.loc[df['Col 2'] == 'High' | (df['Col2'] == 'Medium')]

这是我得到的错误

 cannot compare a dtyped [bool] array with a scalar of type [bool]

任何想法如何使它起作用以及该错误意味着什么?

Any ideas how to make this work and what that error means?

推荐答案

您缺少一对括号来获取|运算符两侧的可比较项-运算符的优先级高于== (请参阅文档):

You are missing a pair of parentheses to get comparable items on both sides of the | operator - which has higher precedence than == (see docs):

df = df.loc[(df['Col 2'] == 'High') | (df['Col2'] == 'Medium')]

这篇关于使用 pandas 过滤多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆