【问题标题】:IndexError Can int be used as indices?IndexError int可以用作索引吗?
【发布时间】:2017-10-28 14:37:28
【问题描述】:

我遇到了一个错误, IndexError:只有整数、切片 (:)、省略号 (...)、numpy.newaxis (None) 和整数或布尔数组是有效的索引。 我正在制作声音识别应用程序。 我的代码是

import numpy as np
import pandas as pd
import scipy as sp
import  pickle
from scipy import fft
from time import localtime, strftime
import matplotlib.pyplot as plt
from skimage.morphology import  disk,remove_small_objects
from skimage.filter import rank
from skimage.util import img_as_ubyte 
import wave

folder = 'mlsp_contest_dataset/'


essential_folder = folder+'essential_data/'
supplemental_folder = folder+'supplemental_data/'
spectro_folder =folder+'my_spectro/'
single_spectro_folder =folder+'my_spectro_single/'
dp_folder = folder+'DP/'

# Each audio file has a unique recording identifier ("rec_id"), ranging from 0 to 644. 
# The file rec_id2filename.txt indicates which wav file is associated with each rec_id.
rec2f = pd.read_csv(essential_folder + 'rec_id2filename.txt', sep = ',')

# There are 19 bird species in the dataset. species_list.txt gives each a number from 0 to 18. 
species = pd.read_csv(essential_folder + 'species_list.txt', sep = ',')
num_species = 19

# The dataset is split into training and test sets. 
# CVfolds_2.txt gives the fold for each rec_id. 0 is the training set, and 1 is the test set.
cv =  pd.read_csv(essential_folder + 'CVfolds_2.txt', sep = ',')

# This is your main label training data. For each rec_id, a set of species is listed. The format is:
# rec_id,[labels]
raw =  pd.read_csv(essential_folder + 'rec_labels_test_hidden.txt', sep = ';')
label = np.zeros(len(raw)*num_species)
label = label.reshape([len(raw),num_species])
for i in range(len(raw)):
    line = raw.iloc[i]
    labels = line[0].split(',')
    labels.pop(0) # rec_id == i
    for c in labels:
        if(c != '?'):
            print(label)
            label[i,c] = 1

我运行这段代码, 我在这一点上遇到了错误 label[i,c] = 1 。 我试图通过print(label) 看到label 变量 label 就像

warn(skimage_deprecation('The `skimage.filter` module has been renamed '
[[ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  0.]
 ...,
 [ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  0.]]

我认为,错误意味着整数、切片 (:)、省略号 (...)、numpy.newaxis (None) 和整数或布尔值不能用作数组索引,但我多次将 int 放入数组索引中,所以我不明白为什么会发生这个错误。 调试告诉我,

labels

有标签:: ['?'] .

c

for c in labels[i]:

有'?',我真的无法理解?类型。我想这个?导致错误,但我不知道如何解决这个问题。 我该如何解决这个问题?

【问题讨论】:

  • for c in labels: ...,但labels 是一个字符串列表。字符串不在集合“整数、切片 (:)、省略号 (...)、numpy.newaxis (None) 和整数或布尔值”中。 (另请注意:np.zeros((len(raw),num_species)) 更简单。)
  • @AndrasDeak 非常感谢!你告诉我的 np.zeros((len(raw),num_species)) 是哪一部分?我该如何解决这个问题?
  • 我只注意到for循环之前的两行可以在一行中完成,而无需重塑。至于您的问题:我不知道您要做什么,但是尝试将字符用作 numpy 数组索引肯定行不通。
  • @AndrasDeak thx。我添加了我的代码信息,如果你知道请帮助我。
  • 问题不是“?”,问题是'?'是一个字符串(调试器告诉你有一个列表,里面有一个字符串)。它可能是'1' 并且同样是错误的。你所做的只是没有意义,你的编辑也没有帮助澄清一点。

标签: python numpy scipy


【解决方案1】:

错误信息是在索引 numpy 数组时

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

label 是一个二维浮点数组,当前值为 0。:

label = np.zeros([len(raw),num_species])

在循环中:

for i in range(len(raw)):        # i=0,1,2,...

你检查过raw 是什么样的吗?来自pd.read_csv 我想这是一个数据框; iloc[i] 选择了一行,但还没有拆分成列?

    line = raw.iloc[i]
    labels = line[0].split(',')
    labels.pop(0) # rec_id == i

labels 是什么样的?我猜它是任何字符串数组

    for c in labels:
        if(c != '?'):          # evidently `c` is a string
            print(label)       # prints the 2d array
            label[i,c] = 1

二维数组的索引应该类似于label[0,1]c 可能是错误消息中的其他内容之一。但不能是字符串。

Dataframe 确实允许使用字符串进行索引 - 这是 pandas 的一项功能。但是 numpy 数组必须有数字索引,或者一些替代品。它们不使用字符串索引(结构化数组除外)。


In [209]: label = np.zeros((3,5))
In [210]: label
Out[210]: 
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
In [211]: label[1,3]
Out[211]: 0.0
In [212]: label[1,3]=1      # index with integers OK
In [213]: label[0,2]=1
In [214]: label[0,'?'] =1    # index with a string - ERROR
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-214-3738f623c78e> in <module>()
----> 1 label[0,'?'] =1

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

In [215]: label[0,:] =2     # index with a slice
In [216]: label
Out[216]: 
array([[ 2.,  2.,  2.,  2.,  2.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

【讨论】:

    猜你喜欢
    • 2016-07-11
    • 2013-11-30
    • 2020-03-04
    • 1970-01-01
    • 2010-09-29
    • 2016-11-27
    相关资源
    最近更新 更多