将列表中的浮点数近似为标量整数时抛出错误

我试图将列表中的浮点数近似为标量整数值。也就是说,我试图将小于 0.5 的值转换为 0,并将大于或等于 0.5 的值转换为 1。但我收到错误。


我的列表值如下所示:


0.2943,

0.3483,

0.3359,

0.3671,

0.6788,

1,

0.779

预期输出:


0,

0,

0,

0,

1,

1,

1

编写的代码:


listSample = []

listSample = list(y_predAN_PCA)


for i in listSample:

    if listSample[i] < 0.5:

        listSample[i] = 0

    else:

        listSample[i] = 1

但我收到以下错误:


类型错误:只有整数标量数组可以转换为标量索引


蝴蝶刀刀
浏览 206回答 3
3回答

RISEBY

你已经得到了别人的答案。如果您使用第三方库没有问题,您可以使用 NumPy 数组进行掩码。对于这样一个小的示例案例,这将是一种矫枉过正,但了解选项仍然很好。说明: lst<0.5返回值小于 0.5 的数组索引。然后将其作为索引传递给数组lst,lst[lst<0.5]并重新分配这些值0。类似地,您检查大于等于 0.5 的值并将它们重新分配为 1。import numpy as nplst = np.array([0.2943,0.3483,0.3359,0.3671,0.6788,1,0.779])lst[lst<0.5] = 0lst[lst>=0.5] = 1print (lst)# array([0., 0., 0., 0., 1., 1., 1.])Jon Clements建议的另一种更好的方法是使用np.where。在这里,您首先指定条件(lst<0.5此处)。如果条件为True,则条件后的第一个值将分配给数组元素。如果条件为False,则将分配第二个值。np.where(lst<0.5, 0, 1)# array([0., 0., 0., 0., 1., 1., 1.])

慕少森

您在代码片段中错误地使用了 for 循环。在您的代码中,我指的是列表中的第i个值,而不是第i个索引。下面的代码可以提供帮助。range 函数将根据列表的长度生成索引。for i in range(len(listSample)):&nbsp; &nbsp; if listSample[i] < 0.5:&nbsp; &nbsp; &nbsp; &nbsp; listSample[i] = 0&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; listSample[i] = 1

ibeautiful

您正在迭代项目而不是项目索引;用于enumerate获取两者:listSample = list(y_predAN_PCA)for i,s in enumerate(listSample):&nbsp; &nbsp; if s < 0.5:&nbsp; &nbsp; &nbsp; &nbsp; listSample[i] = 0&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; listSample[i] = 1更好的是,使用round和列表理解:listSample = [round(e) for e in listSample]或者,如果您使用的是 NumPy:listSample = np.round(listSample)注意:这会将 0.5向下舍入为 0(“银行家的舍入”)并返回浮点数列表。更接近您的代码(对于正数)将是:listSample = [int(e+0.5) for e in listSample]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python