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

I have an array of indexes:test_idxs = np.array([4, 2, 7, 5])I also have an array of values (which is

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.])

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745619125a4636414.html

相关推荐

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

    I have an array of indexes:test_idxs = np.array([4, 2, 7, 5])I also have an array of values (which is

    9小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信