首页 > 解决方案 > 这是什么意思,我该如何解决?

问题描述

我正在尝试为未来的异常创建一个多维数组。这个错误不断弹出。有什么问题?我之前对更大的数组使用了相同的代码,试图缩短它,现在它有很多错误。

import numpy as np
import csv

    emptystns=[]
    with open('stationlist2.tsv') as i:
    j = csv.reader(i, delimiter='\t')
    next (j)
    for r in j:
        emptystns.append(r[0]) 



    lines = []

    ns = sum(1 for line in open('stationlist2.tsv'))-1
        #3660 stations (minus the headerline which is not a stationid)
    nmons = 12
        #12 months in a year
    nlays = 8
        #the number of depths in layers is the number of layers
    stnslist= []

    data=np.ma.masked_all((ns, nlays, nmons), dtype=np.float64)  

    with open ('SoilAverage1981.tsv', 'r') as f:
    reader= csv.reader(f,delimiter = '\t')
    next(reader)

    for line in reader:
        temp = line[2:]
        istn= emptystns.index(line[0])
        ilayers = line[1]

        for i, info in enumerate(temp):                         
            imonth = i
            if info !='':
                data[istn, ilayers, imonth] = info

print 'done'

错误信息:

IndexError: only integers, slices (`:`), ellipsis (`...`),     numpy.newaxis (`None`) and integer or boolean arrays are valid indices

标签: pythonjupyter-notebookjupyter

解决方案


我会做一个有根据的猜测,因为似乎只有一个地方可以索引一个 numpy 数组:

data[istn, ilayers, imonth]

data,检查它的shapedtype

查看指数,istnilayersimonth。错误提供的列表中是否有任何内容?可能是一个字符串,可能是一个浮点数或列表?

integers, 
slices (`:`), 
ellipsis (`...`),     
numpy.newaxis (`None`) 
integer or boolean arrays 

调试这样的错误的基础知识:

  • 确定错误发生的位置

  • 识别表达式中的所有变量

  • 验证这些变量的标识和/或属性

  • 哪些与错误消息匹配或与记录的行为不匹配。


推荐阅读