简体   繁体   English

布尔索引,尝试按标签搜索有两个条件,但布尔和、按位 & 和 numpy logical_and 都返回错误

[英]Boolean indexing, trying to search by label with two conditions but boolean and, bitwise &, and numpy logical_and all return errors

I am trying to return the rows of a dataframe in pandas that correspond to the label I choose.我正在尝试返回与我选择的标签相对应的 Pandas 中数据帧的行。 For example, in my function Female, it returns all the rows in which the patient is female.例如,在我的函数Female 中,它返回患者为女性的所有行。 For AgeRange, I have run into issues satisfying both conditions without getting an error.对于 AgeRange,我遇到了满足这两个条件而没有出现错误的问题。

dataset = pd.read_csv('insurance.csv')

def Female(self):
    rows = dataset[dataset.sex == 1]
    print(rows)

def AgeRange(self):
    rows = dataset[dataset.age > 0] & dataset[dataset.age < 20]
    print(rows)

Using the bitwise operator gets be the error below: TypeError: unsupported operand type(s) for &: 'float' and 'bool'使用按位运算符会出现以下错误:TypeError: 不支持的操作数类型 (s) for &: 'float' 和 'bool'

def AgeRange(self):
    rows = dataset[dataset.age > 0] and dataset[dataset.age < 20]
    print(rows)

Using the boolean and operator gets me the error below: ValueError: The truth value of a DataFrame is ambiguous.使用布尔值和运算符会得到以下错误: ValueError:DataFrame 的真值不明确。 Use a.empty, a.bool(), a.item(), a.any() or a.all().使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

def AgeRange(self):
    rows = np.logical_and(dataset[dataset.age > 0],dataset[dataset.age < 20])
    print(rows)

Using the numpy logical and gets me the error: ValueError: operands could not be broadcast together with shapes (1309,7) (135,7).使用 numpy 逻辑并让我得到错误:ValueError: 操作数无法与形状 (1309,7) (135,7) 一起广播。

I'm honestly not sure what that leaves me with, or what is causing the issue in the first place.老实说,我不确定这给我留下了什么,或者首先是什么导致了这个问题。 Can anyone help point out where I'm going wrong?谁能帮忙指出我哪里出错了?

Standard syntax is标准语法是

df[(df['a'] > X) & (df['a'] < Y)]

or using query():或使用查询():

df.query('X < a < Y') 

This syntax is easier for me!这种语法对我来说更容易! If you hace 3 diferent conditions that want to meet at the same time如果你有3个不同的条件想要同时满足

cond1 = df["id"] == id
cond2  = df["date"] > date_min
cond3  = df["date"] < date_max

result = df[cond1 & cond2 & cond3]

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

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