【发布时间】:2013-07-30 12:16:56
【问题描述】:
您好,我想使用另一个数组中的值,使用元组列表作为索引
代码:
import numpy as np
elevation_array = np.random.rand(5,5) #creates a random array 5 by 5
sort_idx = np.argsort(elevation_array, axis=None)
new_idx = zip(*np.unravel_index(sort_idx[::-1], elevation_array.shape))
for r, c in new_idx:
r, c = [r, c]
for [x, y], elevation in np.ndenumerate(elevation_array):
print elevation[r, c] # I will want to for other stuff here later on
我也试过这样:
for r, c in new_idx:
r, c = [r, c]
for elevation in np.ndenumerate(elevation_array):
print elevation[r, c]
我得到了第一个错误:
IndexError: 0-d arrays can only use a single () or a list of newaxes (and a single ...) as an index
任何帮助都会很棒,而且解释会非常有用,因为我是 python 新手
在第二个我得到错误:
tuple indices must be integers, not tuple
回答:
for r, c in new_idx:
print elevation_array[r, c]
我得到它是如此简单,我不敢相信我不知道该怎么做! :)
【问题讨论】:
-
究竟是什么导致了您的错误?您打印的所有代码对我来说都运行良好。
-
Appologies 我没有放给出错误的代码。我希望按照从最大值到最小值的顺序打印出 elevation_array,这些值作为索引存储在 new_idx 数组中。这有意义吗?
-
将
elevation[r, c]更改为elevation_array[r, c]。elevation是一个标量,而不是一个数组,因此它不能被索引。 -
@Jamie 这样做似乎会打印出每个值的整个数组?例如 25x 最高数字,然后 25 x 下一个最高数字等...
-
我想我做到了!哇!
标签: python sorting loops numpy indexing