在本文中,我们将详细介绍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索引错误)
- IndexError:只有整数、切片 (`:`)、省略号 (`...`)、numpy.newaxis (`None`) 和整数或布尔数组是有效的索引,我该如何解决?
- IndexError:只有整数、切片`:`、省略号`...`、numpy.newaxis`None`和整数或布尔数组是有效的索引错误
- IndexError:索引过多。具有1行2列的Numpy数组
- numpy array:IndexError:数组索引过多
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`) 和整数或布尔数组是有效的索引,我该如何解决?
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt2
import matplotlib.cm as cm
import numpy as np # linear algebra
import pandas as pd
kanser = pd.read_csv(''breast-cancer-wisconsin.csv'') #veri seti okuma
kanser.dropna(inplace=True) #kayıp değerlerin olduğu yerleri kaldırma
kanser.Class = [1 if i == "benign" else 0 for i in kanser.Class] #target için tür döüşümü yapma
X=kanser.drop(''Class'',axis = 1)
y=kanser.Class.values
from sklearn.manifold import TSNE
tsne = TSNE(verbose=1,perplexity=40,n_iter= 4000)
Y = tsne.fit_transform(X)
from sklearn.cluster import KMeans
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'')
kY = kmns.fit_predict(X)
f,(ax1,ax2) = plt.subplots(1,2,sharey=True)
ax1.scatter(Y[:,0],Y[:,1],c=kY,cmap = "jet",edgecolor = "None",alpha=0.35)
ax1.set_title(''k-means clustering plot'')
ax2.scatter(Y[:,c = y[''Class''],alpha=0.35)
ax2.set_title(''Actual clusters'')
我收到此错误。
IndexError Traceback (most recent call last)
<ipython-input-3-fd6a6e8ca8a9> in <module>()
26 ax1.set_title(''k-means clustering plot'')
27
---> 28 ax2.scatter(Y[:,alpha=0.35)
29 ax2.set_title(''Actual clusters'')
IndexError: only integers,slices (`:`),ellipsis (`...`),numpy.newaxis (`None`) and integer or boolean arrays are valid indices
我能为此做什么?
解决方法
我运行了您的代码并查看了变量。您的对象“y”似乎是一个列表,其 _getitem_ 方法不接受字符串。
from sklearn import datasets
data = datasets.load_breast_cancer()
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt2
import matplotlib.cm as cm
import numpy as np # linear algebra
import pandas as pd
# kanser = pd.read_csv(''breast-cancer-wisconsin.csv'') #veri seti okuma
kanser = pd.DataFrame(data.data,columns = data.feature_names)
kanser[''Class''] = data.target_names[data.target]
kanser.dropna(inplace=True) #kayıp değerlerin olduğu yerleri kaldırma
kanser.Class = [1 if i == "benign" else 0 for i in kanser.Class] #target için tür döüşümü yapma
X=kanser.drop(''Class'',axis = 1)
y=kanser.Class.values
from sklearn.manifold import TSNE
tsne = TSNE(verbose=1,perplexity=40,n_iter= 4000)
Y = tsne.fit_transform(X)
from sklearn.cluster import KMeans
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'')
kY = kmns.fit_predict(X)
f,(ax1,ax2) = plt.subplots(1,2,sharey=True)
ax1.scatter(Y[:,0],Y[:,1],c=kY,cmap = "jet",edgecolor = "None",alpha=0.35)
ax1.set_title(''k-means clustering plot'')
xs = Y[:,0]
ys = Y[:,1]
print(f''y = {y}'')
cs = y[''Class'']
ax2.scatter(xs,ys,c = cs,alpha=0.35)
ax2.set_title(''Actual clusters'')
输出:
[t-SNE] Computing 121 nearest neighbors...
[t-SNE] Indexed 569 samples in 0.001s...
[t-SNE] Computed neighbors for 569 samples in 0.018s...
[t-SNE] Computed conditional probabilities for sample 569 / 569
[t-SNE] M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1 1 1 1 0 1
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
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
1 1 1 1 1 1 1 0 0 0 0 0 0 1]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-5-73736c0bb107> in <module>()
37 print(f''y = {y}'')
38
---> 39 cs = y[''Class'']
40
41
IndexError: only integers,slices (`:`),ellipsis (`...`),numpy.newaxis (`None`) and integer or boolean arrays are valid indices
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数组
当我尝试仅获取像这样的数组的第一个元素时
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:数组索引过多
这有效:
>>> 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:数组索引过多的相关信息,请在本站查询。
本文标签: