gpt4 book ai didi

python - 类型错误 : only integer arrays with one element can be converted to an index 3

转载 作者:IT老高 更新时间:2023-10-28 22:21:43 28 4
gpt4 key购买 nike

我在标题中有这个错误,不知道出了什么问题。当我使用 np.hstack 而不是 np.append 时它可以工作,但我想让它更快,所以使用 append。

time_list a list of floats

heights is a 1d np.array of floats

j = 0
n = 30
time_interval = 1200
axe_x = []

while j < np.size(time_list,0)-time_interval:
if (not np.isnan(heights[j])) and (not np.isnan(heights[j+time_interval])):
axe_x.append(time_list[np.arange(j+n,j+(time_interval-n))])

 File "....", line .., in <module>
axe_x.append(time_list[np.arange(j+n,j+(time_interval-n))])

TypeError: only integer arrays with one element can be converted to an index

最佳答案

问题正如错误所示,time_list 是一个普通的 python 列表,因此您不能使用另一个列表对其进行索引(除非另一个列表是具有单个元素的数组)。示例 -

In [136]: time_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]

In [137]: time_list[np.arange(5,6)]
Out[137]: 6

In [138]: time_list[np.arange(5,7)]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-138-ea5b650a8877> in <module>()
----> 1 time_list[np.arange(5,7)]

TypeError: only integer arrays with one element can be converted to an index

如果您想进行这种索引,您需要将 time_list 设为 numpy.array。示例 -

In [141]: time_list = np.array(time_list)

In [142]: time_list[np.arange(5,6)]
Out[142]: array([6])

In [143]: time_list[np.arange(5,7)]
Out[143]: array([6, 7])

另外需要注意的是,在你的 while 循环中,你永远不会增加 j,所以它可能会以无限循环结束,你也应该增加 j 一些量(可能是 time_interval ?)。


但是根据你在评论中发布的要求-

axe_x should be a 1d array of floats generated from the time_list list

您应该使用 .extend() 而不是 .append().append 会为您创建一个数组列表。但如果需要一维数组,则需要使用.extend()。示例 -

time_list = np.array(time_list)
while j < np.size(time_list,0)-time_interval:
if (not np.isnan(heights[j])) and (not np.isnan(heights[j+time_interval])):
axe_x.extend(time_list[np.arange(j+n,j+(time_interval-n))])
j += time_interval #Or what you want to increase it by.

关于python - 类型错误 : only integer arrays with one element can be converted to an index 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33144039/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com