Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

python - How to rearrange array based upon index array

I'm looking for a one line solution that would help me do the following.

Suppose I have

array = np.array([10, 20, 30, 40, 50])

I'd like to rearrange it based upon an input ordering. If there were a numpy function called arrange, it would do the following:

newarray = np.arrange(array, [1, 0, 3, 4, 2])
print newarray

    [20, 10, 40, 50, 30]

Formally, if the array to be reordered is m x n, and the "index" array is 1 x n, the ordering would be determined by the array called "index".

Does numpy have a function like this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can simply use your "index" list directly, as, well, an index array:

>>> arr = np.array([10, 20, 30, 40, 50])
>>> idx = [1, 0, 3, 4, 2]
>>> arr[idx]
array([20, 10, 40, 50, 30])

It tends to be much faster if idx is already an ndarray and not a list, even though it'll work either way:

>>> %timeit arr[idx]
100000 loops, best of 3: 2.11 μs per loop
>>> ai = np.array(idx)
>>> %timeit arr[ai]
1000000 loops, best of 3: 296 ns per loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...