如何在python中使用或运算符从csv中的列中选择多个值

我试图计算在一个spectific列“y”中具有数字2或3,4或5的人的百分比,但我得到以下错误:TypeError:|不支持的操作数类型:“str”和“bool”


这是我的代码:


All = df.shape[0]

Seizure = df[df['y'] == 1]

nonSeizure = (df[df['y'] == 2]) | (df[df['y'] == 3]) | (df[df['y'] == 4]) | (df[df['y'] == 5])


x = len(Seizure)/All

y = len(nonSeizure)/All


print('Seizure :',x*100,'%')

print('non Seizure :',y*100,'%')


慕斯王
浏览 129回答 2
2回答

肥皂起泡泡

您可以使用熊猫数据帧的功能来实现所需的结果。isinisin() 函数用于检查 DataFrame 中的每个元素是否包含在值中。以下是您可能想要尝试的代码,lst = [2, 3, 4, 5] # --> declare the listAll = df.shape[0]Seizure = df[df['y'] == 1]nonSeizure = df[df['y'].isin(lst)]x = len(Seizure)/Ally = len(nonSeizure)/Allprint('Seizure :',x*100,'%')print('non Seizure :',y*100,'%')

蛊毒传说

使用 ,因为它是一种更 python 的方式。您的代码可能会以这种方式编码。nonSeizure = df.loc[df['y'].isin([2, 3, 4, 5])]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python