使用元组列表在另一个数组中索引值

时间:2013-07-30 11:15:32

标签: python sorting loops numpy indexing

您好我想使用元组列表作为索引来使用另一个数组中的值

代码:

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] 

我知道这么简单,我无法相信我不知道该怎么做! :)

1 个答案:

答案 0 :(得分:0)

你可以得到相同的结果:

print np.sort(elevation_array.flat)[::-1]