如何使用循环计算Python中的值
我想数一数表中的真数。我写了这段代码,但它总是返回如何使用循环计算Python中的值,python,list,Python,List,我想数一数表中的真数。我写了这段代码,但它总是返回0。我该怎么办 def count(numbers): total = 0 for x in numbers: if x == "True": total += 1 return total count(data['diabetes']) 如果它是一个DataFrame,您可以count()通过以下方式计算所选列适合您的条件的行数:
0
。我该怎么办
def count(numbers):
total = 0
for x in numbers:
if x == "True":
total += 1
return total
count(data['diabetes'])
如果它是一个
DataFrame
,您可以count()
通过以下方式计算所选列适合您的条件的行数:
data[(data['diabetes'] == True)].count()
或者只测量长度
:
len(data[(data['diabetes'] == True)])
表的真值必须为True,而不是字符串“True”。可以在if语句中直接检查真值,如下所示:
if x is True:
print("Yes")
或者简单地说
if x:
print("Yes")
现在代码变成:
def count(numbers):
total = 0
for x in numbers:
if x:
total += 1
return total
count(data['diabetes'])
您计算的字符串数正好是
“True”
…您能澄清您的问题吗?数据['diabetes']
的输入是什么样子的?“True”是什么意思(是您现在正在测试的字符串,还是值True
?