[英]"slice indices must be integers" error when splitting a data array
你能帮我解决这个问题吗? x 已经是 integer。 但是我遇到了这个问题,如果我使用 90 而不是 x,代码会运行但使用 x 变量不起作用。
split_ratio=[3,1,1]
x=split_ratio[0]/sum(split_ratio)*data.shape[0]
print(x)
print(data[0:x,:])
Output;
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
您可以从 output 中看到该数字是浮点数( 90.0
)而不是整数( 90
)。 只需转换为int
就像 -
x=int(split_ratio[0]/sum(split_ratio)*data.shape[0])
每当您除以/
时,它总是返回浮点数而不是integer ,尽管答案可能是 integer (小数点后没有任何内容)。
要解决这个问题,有两种方法,一种是使用int()
function,另一种是使用地板除法//
。
所以,你可以做
x=int(split_ratio[0]/sum(split_ratio)*data.shape[0])
或者
x=split_ratio[0]//sum(split_ratio)*data.shape[0]
现在,当您执行print(x)
时,output 将是90
而不是90.0
,因为90.0
意味着它是一个浮点数,而90
意味着它现在是一个 integer。
将字符串拼接成列表等可迭代对象时,不能使用浮点数。 以下面的代码为例说明不应该做什么
例子
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]
由于使用了一个浮点数,其中 integer 应该是
结果
TypeError:切片索引必须是整数或无或具有索引方法
一个解决方法是在int()
中包含bad
的值,它应该将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:])
#注意:索引时x
后面的逗号应该去掉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.