Python numpy 索引超出轴零范围
Python numpy index is out of bound for axis zero
我有一个用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])
虽然第一次打印的结果是 3,316,888,但我在最后一次打印时收到以下错误:
IndexError: index 1658944 is out of bounds for axis 0 with size 1658944
知道为什么我的数组会出现这个错误吗?
您的 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
考虑到您的问题是多么神秘,我会继续使用 try/except 循环对其进行测试,以确保代码通过该点并且仅在索引 1658944 处出现问题...
类似于:
for x in range(sortedList.size):
try:
sortedList[x]
except:
print "no index at", x
报告你的结果。
感谢所有评论。我认为我的问题是 sortedList.size returns 数组中元素的总数,而我期望数组中的元组数量(因为 sortedList 是元组列表 [[],[]. ..])。所以我使用 sortedList.shape
解决了我的问题
我有一个用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])
虽然第一次打印的结果是 3,316,888,但我在最后一次打印时收到以下错误:
IndexError: index 1658944 is out of bounds for axis 0 with size 1658944
知道为什么我的数组会出现这个错误吗?
您的 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
考虑到您的问题是多么神秘,我会继续使用 try/except 循环对其进行测试,以确保代码通过该点并且仅在索引 1658944 处出现问题...
类似于:
for x in range(sortedList.size):
try:
sortedList[x]
except:
print "no index at", x
报告你的结果。
感谢所有评论。我认为我的问题是 sortedList.size returns 数组中元素的总数,而我期望数组中的元组数量(因为 sortedList 是元组列表 [[],[]. ..])。所以我使用 sortedList.shape