ahajib
ahajib

Reputation: 13520

Python numpy index is out of bound for axis zero

I have a code written in Python similar to the following:

def adamic_adar_prediction(graph):
    adjacencyMatrix = graph.get_adjacency()
    AAMatrix = adamic_adar_score(graph)
    AAMatrix  = np.array(AAMatrix)
    i = (-AAMatrix ).argsort(axis=None, kind='mergesort')
    j = np.unravel_index(i, AAMatrix .shape)
    sortedList = np.vstack(j).T
    print(sortedList.size)

    print(sortedList[1658943])
    print(sortedList[1658945])

While the result of the first print is 3,316,888 I receive the following error for the last print:

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

Any idea why this error arises for my array?

Upvotes: 2

Views: 18691

Answers (3)

ahajib
ahajib

Reputation: 13520

Thanks for all of the comments. I figured my problem is that sortedList.size returns total number of elements in the array while I was expecting the number of tuples in my array (since sortedList is a list of tuples [[],[],...]). So I solved my problem using sortedList.shape

Upvotes: 2

stoves
stoves

Reputation: 798

Considering how mysterious your problem is, I'd go ahead and test this with a try/except loop to be sure the code goes past that point and is only having issues at index 1658944...

something like:

for x in range(sortedList.size):
    try:
        sortedList[x]
    except:
        print "no index at", x

Report back what your results are.

Upvotes: 2

Akavall
Akavall

Reputation: 86306

You don't have enough elements in your array, for example:

In [5]: import numpy as np

In [6]: a = np.array([1,2])

In [8]: a[2] # there is no element at 2nd index
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-8-016a87a854bc> in <module>()
----> 1 a[2]

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

Upvotes: 2

Related Questions