简体   繁体   English

来自数据框,熊猫中单个列的多个条件

[英]Multiple conditions from single column in dataframe, pandas

I am trying to select a subset from a single dataframe column, and I need help applying two conditions on a single column. 我正在尝试从单个数据框列中选择一个子集,并且我需要在单个列上应用两个条件的帮助。 For example, how do I select for both "Tom" and "Chris" in the table below? 例如,如何在下表中同时选择“汤姆”和“克里斯”?

import pandas as pd
dic={"Name":["Chris","Tom","Steven"], "Age":[12,34,55]}
dic={"Name":["Chris","Tom","Steven"], "Age":[12,34,55]}
df=pd.DataFrame(dic)
df[df["Name"]=="Tom"]

Why is it that when I use df[df["Name"]==("Chris" or "Tom")] it picks "Chris, but when or is replaced by and, "Tom" is selected? 为什么当我使用df[df["Name"]==("Chris" or "Tom")]会选择“ Chris,但是当and替换为and时,选择了” Tom“?

when we check condition1 OR condition2 - it's enough if first condition/operand is True , so if the first one is True - the second will not be checked (because it's enough to have one True ): 当我们检查condition1 OR condition2 -如果第一个条件/操作数为True就足够了,所以如果第一个条件/操作数为True检查第二个条件/操作数(因为拥有一个True足够了):

In [247]: 1 or 2
Out[247]: 1

for AND we must check also the second one if the first one is True (because all conditions must be True ): 对于AND,我们还必须检查第二个条件是否第一个条件为True (因为所有条件都必须为True ):

In [248]: 1 and 2
Out[248]: 2

but if the first condition is False we don't need to check the second one (because it's enough to have one False - it'll make the whole "thing" False ): 但是,如果第一个条件为False我们就不必检查第二个条件(因为足以使一个条件为False ,它将使整个“事物”为False ):

In [250]: 0 and 1
Out[250]: 0

The same logic will be applied to strings (NOTE: empty strings will be evaluated as False ): 相同的逻辑将应用于字符串(注意:空字符串将被评估为False ):

In [242]: ("Chris" or "Tom")
Out[242]: 'Chris'

In [249]: ("Chris" and "Tom")
Out[249]: 'Tom'

so when you do 所以当你这样做

df[df["Name"]==("Chris" or "Tom")]

it's the same as: 它与:

df[df["Name"]=="Chris"]

how to do it properly (in a Pandas way) : 如何正确地做到这一点(以熊猫的方式)

In [243]: df[df["Name"].isin(["Chris","Tom"])]
Out[243]:
   Age   Name
0   12  Chris
1   34    Tom

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

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