0

I've data iris in UCI. I want to group it by its class. I used this code:

def splitData(trainingSet, classedTrainingSet=[], listClass=[]):
    for x in range(len(trainingSet)):
        classData = trainingSet[x][-1] #string
        if classData not in listClass:
            listClass.append(classData)
        for y in range(len(listClass)):
            if listClass[y] == classData:
                classedTrainingSet.append((y, trainingSet[x]))

The error was:

IndexError: tuple index out of range

How can I group the data by its class?

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
  • The code you pasted is not indented correctly, can you edit and fix it? – Abhinav Upadhyay Sep 18 '18 at 09:46
  • which line you are getting the error??? – Praveen Sep 18 '18 at 09:46
  • 1
    Don't use `range()` and indexed access, python `for` loops are made to iterate on a sequence, ie : `for char in ['a', 'b', 'c']: print(char)`. This is more efficient, much more readable, works with every iterable (not only sequences), and avoids quite a few IndexError (note that it will necessarily solve your problem here but anyway). Also, beware of the "mutable default argument" gotcha cf https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – bruno desthuilliers Sep 18 '18 at 09:54

1 Answers1

0

You get this error if the tuple is empty while getting the last element

In [1]: emptyTuple = ()    
In [2]: emptyTuple[-1]    
IndexError: tuple index out of range

classData = trainingSet[x][-1] #string can replaced with

if len(trainingSet[x]) > 0:
    classData = trainingSet[x][-1]
Praveen
  • 8,945
  • 4
  • 31
  • 49