最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

python - Reorder Numpy array by given index list - Stack Overflow

matteradmin6PV0评论

I have an array of indexes:

test_idxs = np.array([4, 2, 7, 5])

I also have an array of values (which is longer):

test_vals = np.array([13, 19, 31, 6, 21, 45, 98, 131, 11])

So I want to get an array with the length of the array of indexes, but with values from the array of values in the order of the array of indexes. In other words, I want to get something like this:

array([21, 31, 131, 45])

I know how to do this in a loop, but I don't know how to achieve this using Numpy tools.

I have an array of indexes:

test_idxs = np.array([4, 2, 7, 5])

I also have an array of values (which is longer):

test_vals = np.array([13, 19, 31, 6, 21, 45, 98, 131, 11])

So I want to get an array with the length of the array of indexes, but with values from the array of values in the order of the array of indexes. In other words, I want to get something like this:

array([21, 31, 131, 45])

I know how to do this in a loop, but I don't know how to achieve this using Numpy tools.

Share Improve this question edited Nov 18, 2024 at 12:39 simon 5,6551 gold badge16 silver badges29 bronze badges asked Nov 18, 2024 at 12:11 IzaeDAIzaeDA 3976 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

This is actually extremely simple with numpy, just index your test_vals array with test_idx (integer array indexing):

out = test_vals[test_idxs]

Output:

array([ 21,  31, 131,  45])

Note that this requires the indices to be valid. If you have indices that could be too high you would need to handle them explicitly.

Example:

test_idxs = np.array([4, 2, 9, 5])
test_vals = np.array([13, 19, 31, 6, 21, 45, 98, 131, 11])

out = np.where(test_idxs < len(test_vals),
               test_vals[np.clip(test_idxs, 0, len(test_vals)-1)],
               np.nan)

Output:

array([21., 31., nan, 45.])
Post a comment

comment list (0)

  1. No comments so far