GVKun编程网logo

numpy python中的“ IndexError:索引过多”(python索引错误)

2

在本文中,我们将详细介绍numpypython中的“IndexError:索引过多”的各个方面,并为您提供关于python索引错误的相关解答,同时,我们也将为您带来关于IndexError:只有整数、

在本文中,我们将详细介绍numpy python中的“ IndexError:索引过多”的各个方面,并为您提供关于python索引错误的相关解答,同时,我们也将为您带来关于IndexError:只有整数、切片 (`:`)、省略号 (`...`)、numpy.newaxis (`None`) 和整数或布尔数组是有效的索引,我该如何解决?、IndexError:只有整数、切片`:`、省略号`...`、numpy.newaxis`None`和整数或布尔数组是有效的索引错误、IndexError:索引过多。具有1行2列的Numpy数组、numpy array:IndexError:数组索引过多的有用知识。

本文目录一览:

numpy python中的“ IndexError:索引过多”(python索引错误)

numpy python中的“ IndexError:索引过多”(python索引错误)

我知道很多人都问过这个问题,但是我无法获得能够解决我的问题的适当答案。

我有一个数组X ::

    X=    [1. 2. -10.]

现在,我试图使矩阵Y读取此X数组。我的代码是:

#   make Y matrixY=np.matrix(np.zeros((len(X),2)))i=0while i < len(load_value):    if X[i,1] % 2 != 0:        Y[i,0] = X[i,0]*2-1    elif X[i,1] % 2 == 0:        Y[i,0] = X[i,0] * 2    Y[i,1] = X[i,2]    i = i + 1print(''Y='')print(Y)

现在,如果运行此命令,它将产生以下错误:

    Traceback (most recent call last):      File "C:\Users\User\Desktop\Code.py", line 251, in <module>        if X[i,1] % 2 != 0:    IndexError: too many indices

在这里,我的数组只有1行。如果我使数组X具有2行或更多行,它不会给我任何错误。仅当X数组具有1行时才给我错误。现在,就我而言,数组X可以具有任意数量的行。它可以有1行或5行或100行。我想编写一个代码,该代码可以读取具有任何行数的数组X,而不会出现任何错误。我怎么解决这个问题?

提前致谢....

答案1

小编典典

我建议使用numpy.matrix代替ndarray,无论您有多少行,它都保持2的尺寸:

In [17]: xOut[17]: array([[0, 1, 2],       [3, 4, 5],       [6, 7, 8]])In [18]: m=np.asmatrix(x)In [19]: m[1]Out[19]: matrix([[3, 4, 5]])In [20]: m[1][0, 1]Out[20]: 4In [21]: x[1][0, 1]---------------------------------------------------------------------------IndexError                                Traceback (most recent call last)<ipython-input-21-bef99eb03402> in <module>()----> 1 x[1][0, 1]IndexError: too many indices

@askewchan提到的Thx,如果要使用numpy数组算法,请使用np.atleast_2d

In [85]: np.atleast_2d(x[1])[0, 1]Out[85]: 4

IndexError:只有整数、切片 (`:`)、省略号 (`...`)、numpy.newaxis (`None`) 和整数或布尔数组是有效的索引,我该如何解决?

IndexError:只有整数、切片 (`:`)、省略号 (`...`)、numpy.newaxis (`None`) 和整数或布尔数组是有效的索引,我该如何解决?

如何解决IndexError:只有整数、切片 (`:`)、省略号 (`...`)、numpy.newaxis (`None`) 和整数或布尔数组是有效的索引,我该如何解决?

  1. import matplotlib as mpl
  2. import matplotlib.pyplot as plt
  3. import matplotlib.pyplot as plt2
  4. import matplotlib.cm as cm
  5. import numpy as np # linear algebra
  6. import pandas as pd
  7. kanser = pd.read_csv(''breast-cancer-wisconsin.csv'') #veri seti okuma
  8. kanser.dropna(inplace=True) #kayıp değerlerin olduğu yerleri kaldırma
  9. kanser.Class = [1 if i == "benign" else 0 for i in kanser.Class] #target için tür döüşümü yapma
  10. X=kanser.drop(''Class'',axis = 1)
  11. y=kanser.Class.values
  12. from sklearn.manifold import TSNE
  13. tsne = TSNE(verbose=1,perplexity=40,n_iter= 4000)
  14. Y = tsne.fit_transform(X)
  15. from sklearn.cluster import KMeans
  16. kmns = KMeans(n_clusters=2,init=''k-means++'',n_init=10,max_iter=300,tol=0.0001,precompute_distances=''auto'',verbose=0,random_state=None,copy_x=True,n_jobs=1,algorithm=''auto'')
  17. kY = kmns.fit_predict(X)
  18. f,(ax1,ax2) = plt.subplots(1,2,sharey=True)
  19. ax1.scatter(Y[:,0],Y[:,1],c=kY,cmap = "jet",edgecolor = "None",alpha=0.35)
  20. ax1.set_title(''k-means clustering plot'')
  21. ax2.scatter(Y[:,c = y[''Class''],alpha=0.35)
  22. ax2.set_title(''Actual clusters'')

我收到此错误。

  1. IndexError Traceback (most recent call last)
  2. <ipython-input-3-fd6a6e8ca8a9> in <module>()
  3. 26 ax1.set_title(''k-means clustering plot'')
  4. 27
  5. ---> 28 ax2.scatter(Y[:,alpha=0.35)
  6. 29 ax2.set_title(''Actual clusters'')
  7. IndexError: only integers,slices (`:`),ellipsis (`...`),numpy.newaxis (`None`) and integer or boolean arrays are valid indices

我能为此做什么?

解决方法

我运行了您的代码并查看了变量。您的对象“y”似乎是一个列表,其 _getitem_ 方法不接受字符串。

  1. from sklearn import datasets
  2. data = datasets.load_breast_cancer()
  3. import matplotlib as mpl
  4. import matplotlib.pyplot as plt
  5. import matplotlib.pyplot as plt2
  6. import matplotlib.cm as cm
  7. import numpy as np # linear algebra
  8. import pandas as pd
  9. # kanser = pd.read_csv(''breast-cancer-wisconsin.csv'') #veri seti okuma
  10. kanser = pd.DataFrame(data.data,columns = data.feature_names)
  11. kanser[''Class''] = data.target_names[data.target]
  12. kanser.dropna(inplace=True) #kayıp değerlerin olduğu yerleri kaldırma
  13. kanser.Class = [1 if i == "benign" else 0 for i in kanser.Class] #target için tür döüşümü yapma
  14. X=kanser.drop(''Class'',axis = 1)
  15. y=kanser.Class.values
  16. from sklearn.manifold import TSNE
  17. tsne = TSNE(verbose=1,perplexity=40,n_iter= 4000)
  18. Y = tsne.fit_transform(X)
  19. from sklearn.cluster import KMeans
  20. kmns = KMeans(n_clusters=2,init=''k-means++'',n_init=10,max_iter=300,tol=0.0001,precompute_distances=''auto'',verbose=0,random_state=None,copy_x=True,n_jobs=1,algorithm=''auto'')
  21. kY = kmns.fit_predict(X)
  22. f,(ax1,ax2) = plt.subplots(1,2,sharey=True)
  23. ax1.scatter(Y[:,0],Y[:,1],c=kY,cmap = "jet",edgecolor = "None",alpha=0.35)
  24. ax1.set_title(''k-means clustering plot'')
  25. xs = Y[:,0]
  26. ys = Y[:,1]
  27. print(f''y = {y}'')
  28. cs = y[''Class'']
  29. ax2.scatter(xs,ys,c = cs,alpha=0.35)
  30. ax2.set_title(''Actual clusters'')

输出:

  1. [t-SNE] Computing 121 nearest neighbors...
  2. [t-SNE] Indexed 569 samples in 0.001s...
  3. [t-SNE] Computed neighbors for 569 samples in 0.018s...
  4. [t-SNE] Computed conditional probabilities for sample 569 / 569
  5. [t-SNE] Mean sigma: 33.679708
  6. [t-SNE] KL divergence after 250 iterations with early exaggeration: 50.078777
  7. [t-SNE] KL divergence after 4000 iterations: 0.221172
  8. y = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  9. 1 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 0 0 1 0 0 1 1 1 1 0 1 0 0 1 1 1 1 0 1 0 0
  10. 1 0 1 0 0 1 1 1 0 0 1 0 0 0 1 1 1 0 1 1 0 0 1 1 1 0 0 1 1 1 1 0 1 1 0 1 1
  11. 1 1 1 1 1 1 0 0 0 1 0 0 1 1 1 0 0 1 0 1 0 0 1 0 0 1 1 0 1 1 0 1 1 1 1 0 1
  12. 1 1 1 1 1 1 1 1 0 1 1 1 1 0 0 1 0 1 1 0 0 1 1 0 0 1 1 1 1 0 1 1 0 0 0 1 0
  13. 1 0 1 1 1 0 1 1 0 0 1 0 0 0 0 1 0 0 0 1 0 1 0 1 1 0 1 0 0 0 0 1 1 0 0 1 1
  14. 1 0 1 1 1 1 1 0 0 1 1 0 1 1 0 0 1 0 1 1 1 1 0 1 1 1 1 1 0 1 0 0 0 0 0 0 0
  15. 0 0 0 0 0 0 0 1 1 1 1 1 1 0 1 0 1 1 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1
  16. 1 0 1 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1
  17. 1 1 0 1 0 1 0 1 1 1 0 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 0
  18. 0 1 0 0 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 1 1 1 1 0 1 1 1 1 1 1
  19. 1 0 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 1 0 1 1 1 1 1 0 1 1
  20. 0 1 0 1 1 0 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 1
  21. 1 1 1 1 1 1 0 1 0 1 1 0 1 1 1 1 1 0 0 1 0 1 0 1 1 1 1 1 0 1 1 0 1 0 1 0 0
  22. 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
  23. 1 1 1 1 1 1 1 0 0 0 0 0 0 1]
  24. ---------------------------------------------------------------------------
  25. IndexError Traceback (most recent call last)
  26. <ipython-input-5-73736c0bb107> in <module>()
  27. 37 print(f''y = {y}'')
  28. 38
  29. ---> 39 cs = y[''Class'']
  30. 40
  31. 41
  32. IndexError: only integers,slices (`:`),ellipsis (`...`),numpy.newaxis (`None`) and integer or boolean arrays are valid indices

IndexError:只有整数、切片`:`、省略号`...`、numpy.newaxis`None`和整数或布尔数组是有效的索引错误

IndexError:只有整数、切片`:`、省略号`...`、numpy.newaxis`None`和整数或布尔数组是有效的索引错误

如何解决IndexError:只有整数、切片`:`、省略号`...`、numpy.newaxis`None`和整数或布尔数组是有效的索引错误

嗨,我有一个坐标列表来选择图像中的某些感兴趣区域。但是当我将这些坐标传递给图像时,我收到了标题中的错误

代码如下:


coord_list =[''[55:130,190:707]'',''[178:280,30:387]'',''[181:273,424:739]'',424:739]'']

image1 = cv2.imread(r''C:\\\\Users\\\\User\\\\Desktop\\\\images\\\\Sample.jpg'')
image1 = cv2.resize(image,(1000,1000))
image_roi = image1[coord_list[0]]
cv2.imshow(''img'',image_roi)
cv2.waitKey(0)



它必须从列表中迭代,因为我必须对文件夹中的许多图像使用相同的坐标

解决方法

您不能直接对索引为字符串的数组进行切片。你必须先评估它:

image_roi = eval(''image1''+coord_list[0])

编辑:

为了回应您的评论,您可以使用 numpy 来表示。 这样就可以直接使用了,不需要使用eval()

import cv2
import numpy as np

coord_list = [np.s_[55:130,190:707],np.s_[178:280,30:387],np.s_[181:273,424:739],np.s_[182:273,424:738] ]
image1 = cv2.imread(''dog.jpg'')
image1 = cv2.resize(image1,(1000,1000))

image_roi = image1[coord_list[0]]
cv2.imshow(''img'',image_roi)
cv2.waitKey(0)

IndexError:索引过多。具有1行2列的Numpy数组

IndexError:索引过多。具有1行2列的Numpy数组

当我尝试仅获取像这样的数组的第一个元素时

import numpya = numpy.array([1,2])a[:,0]

我得到这个错误

--------------------------------------------------------------------------- IndexError                                Traceback (most recent call last)<ipython-input-3-ed371621c46c> in <module>()----> 1 a[:,0]IndexError: too many indices

我想找到一种在仍然使用切片的情况下执行此操作的方法,因为完整的代码会打开,并使用numpy.loadtxt()两列(从1到N之间不等)的所有列读取许多不同的文件。

答案1

小编典典

您的数组a = numpy.array([1,2])只有 一个 维度:其形状为(2,)。然而,你的切片 a[:,0]指定选择 2米
的尺寸。这导致NumPy引发错误。

要从中获取第一个元素,a只需编写即可a[0](此处仅选择一个维度)。


看另一个问题,如果您想确保语法a[:,0]始终有效,则可以确保a始终具有两个维度。np.loadtxt使用ndmin参数加载数组时,例如:

np.loadtxt(F, skiprows=0, ndmin=2)

numpy array:IndexError:数组索引过多

numpy array:IndexError:数组索引过多

这有效:

>>> a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])>>> a[: , 2]array([ 3,  7, 11])

这不是

>>> a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11]])>>> a[:,2]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: too many indices for array

为什么这样 ?

答案1

小编典典

Numpy
ndarray表示所有元素都具有相同的长度。在这种情况下,您的第二个数组不包含相同长度的列表,因此它最终是列表的一维数组,而不是“适当的”二维数组。

来自N维数组的Numpy文档:

ndarray是相同类型和大小的项目的(通常为固定大小)多维容器。

a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])a.shape # (3,4)a.ndim # 2b = np.array([[1,2,3,4], [5,6,7,8], [9,10,11]])b.shape # (3,)b.ndim # 1

我们今天的关于numpy python中的“ IndexError:索引过多”python索引错误的分享已经告一段落,感谢您的关注,如果您想了解更多关于IndexError:只有整数、切片 (`:`)、省略号 (`...`)、numpy.newaxis (`None`) 和整数或布尔数组是有效的索引,我该如何解决?、IndexError:只有整数、切片`:`、省略号`...`、numpy.newaxis`None`和整数或布尔数组是有效的索引错误、IndexError:索引过多。具有1行2列的Numpy数组、numpy array:IndexError:数组索引过多的相关信息,请在本站查询。

本文标签: