python-3.x - 如何修复 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
解决方案
您可以通过编写以下内容来重现您的错误:
Centroid = Centroid=np.array([]).reshape(n,0)
print(Centroid[:, 0])
您正在索引一个空数组,这总是会导致索引错误。
要解决此问题,您应该将 Centroid 初始化为非空数组。
推荐阅读
- apache-spark - Spark Join 优化
- python - 有没有办法在使用 neo4jrestclient 和 python 时在 neo4j 中编写查询?
- javascript - 从本地 json 文件中获取数据
- c# - 为什么显式接口实现以这种方式工作?
- php - 如何动态使用 PHP 脚本作为 img 标签并在 url 中传递文本和图像名称/类型来执行 PHP 脚本
- python - Pyspark 没有选择自定义模式
- tableau-api - 不同日期的2个数据点之间的差异
- python - Scrapy - 从表格中提取文本
- java - JSON 点表示法比层次结构有什么好处?
- flutter - 如何在颤振中修改库?