拆分数据数组时出现"slice indices must be integers"错误



你能帮我解决这个问题吗? x 已经是一个整数。但是我遇到了这个问题,如果我使用 90 而不是 x,代码运行但使用 x 变量不起作用。

split_ratio=[3,1,1]
x=split_ratio[0]/sum(split_ratio)*data.shape[0]
print(x)
print(data[0:x,:])

输出;

90.0
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-38-0e56a1aca0a0> in <module>()
2 x=split_ratio[0]/sum(split_ratio)*data.shape[0]
3 print(x)
----> 4 print(data[0:x,:])
TypeError: slice indices must be integers or None or have an __index__ method

每当你除以/时,它总是返回一个浮点数而不是一个整数,尽管答案可能是一个整数(小数点后没有任何内容).
要解决此问题,有两种方法,一种是使用int()函数,另一种是使用楼层除法//

所以,你可以做

x=int(split_ratio[0]/sum(split_ratio)*data.shape[0])

x=split_ratio[0]//sum(split_ratio)*data.shape[0]

现在,当你要做print(x)输出将是90而不是90.090.0意味着它是一个浮点数,90意味着现在它是一个整数。

从输出中可以看出,该数字是浮点数(90.0)而不是整数(90)。只需转换为int,例如 -

x=int(split_ratio[0]/sum(split_ratio)*data.shape[0])

将字符串拼接为可迭代对象(如列表)时,不能使用浮点数。 以下面的代码为例,说明不该做什么


data = 'hello there'
#bad is a float since 4/3 1.333
bad = 4/3
#here bad is used as the end (`indexing[start:end:step]`). 
indexIt = data[0:bad:1]

由于使用了浮点数,其中整数应该是

结果

类型错误:切片索引必须是整数或无,或者具有索引方法


对此的一种解决方法是将bad的值括在int()中,这将1.333 to 1转换为 (float 到 int)

溶液

data = 'hello there'
bad = int(4/3)
indexIt = data[0:bad:1]
print(indexIt)

结果

"h"

因此,考虑到这一点,您的代码应如下所示

split_ratio=[3,1,1]
x=split_ratio[0]/sum(split_ratio)*data.shape[0]
print(x)
print(data[0:x:])

#Note:应删除索引时x后的逗号。

相关内容

最新更新