Python numpy索引超出z轴的范围

2024-04-25 14:13:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用Python编写的代码,如下所示:

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])

当第一次打印的结果是3316888时,我收到最后一次打印的以下错误:

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

知道为什么我的数组会出现这个错误吗?


Tags: 代码sizeindexdef错误npgraphprint
3条回答

您的array中没有足够的元素,例如:

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

谢谢你的评论。我发现我的问题是sortedList.size返回数组中元素的总数,而我期望的是数组中的元组数(因为sortedList是元组列表[[],[],…])。所以我用sortedList.shape解决了我的问题

考虑到您的问题有多神秘,我将继续使用try/except循环测试这个问题,以确保代码经过那个点,并且只在索引1658944处有问题。。。

类似于:

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

报告你的结果。

相关问题 更多 >