首页 > 解决方案 > 如何修复 IndexError:索引 0 超出轴 1 大小为 0 的范围

问题描述

这是我的代码。程序总是出错并输出

IndexError: index 0 is out of bounds for axis 1 with size 0

这是我第一次学习如何使用 python 编码,我不明白为什么程序会出错。

import pandas as pd
import numpy as np 
import math
from matplotlib import pyplot as plt

data= pd.read_csv('fifa20.csv') data.describe()

X = data.iloc[:, [2, 6]].values

m=X.shape[0] #number of training examples n=X.shape[1] #number of features.Here n=2 n_iter=100

K=4 # number of clusters

Centroid=np.array([]).reshape(n,0)

Output={}

EuclidianDistance=np.array([]).reshape(m,0) 
for k in range(K):
      tempDist=np.sum((X-Centroid[:,k])*2,axis=1)  #I got Index error in this line 
      EuclidianDistance=np.c_[EuclidianDistance,tempDist] 
C=np.argmin(EuclidianDistance,axis=1)+1

标签: python-3.x

解决方案


您可以通过编写以下内容来重现您的错误:

Centroid =  Centroid=np.array([]).reshape(n,0)
print(Centroid[:, 0])

您正在索引一个空数组,这总是会导致索引错误。

要解决此问题,您应该将 Centroid 初始化为非空数组。


推荐阅读