我试图找出如何使用多个条件计算数据帧中出现的次数。 在这个特别的例子中,我想知道第3类中女性乘客的数量
PassengerId Pclass Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 892 3 male 34.5 0 0 330911 7.8292 NaN Q
1 893 3 female 47.0 1 0 363272 7.0000 NaN S
2 894 2 male 62.0 0 0 240276 9.6875 NaN Q
3 895 3 male 27.0 0 0 315154 8.6625 NaN S
4 896 3 female 22.0 1 1 3101298 12.2875 NaN S
以下是我几次失败的尝试:
len(test[test["Sex"] == "female", test["Pclass"] == 3])
sum(test.Pclass == 3 & test.Sex == "female")
test.[test["Sex"] == "female", test["Pclass"] == 3].count()
他们似乎都没有工作。 最后,我创建了自己的函数,但必须有一种更简单的方法来计算它
def countif(sex, pclass):
x = 0
for i in range(0,len(test)):
s = test.iloc[i]['Sex']
c = test.iloc[i]['Pclass']
if s == sex and c == pclass:
x = x + 1
return x
先谢谢你
有几种方法可以做到这一点:
您需要将布尔值放在圆括号中,并用&
或者你可以:
相关问题 更多 >
编程相关推荐