替换索引数组中与另一个数组对应的值 [英] Replace values in array of indexes corresponding to another array

查看:183
本文介绍了替换索引数组中与另一个数组对应的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大小为[1, x]的值数组A和一个大小为[1, y](y> x)的索引数组B与数组A对应.因此,我想要一个大小为[1,y]的数组C,其中填充了A的值.

I have an array A of size [1, x] of values and an array B of size [1, y] (y > x) of indexes corresponding to array A. I want as result an array C of size [1,y] filled with values of A.

以下是输入和输出的示例:

Here is an example of inputs and outputs:

>>> A = [6, 7, 8]
>>> B = [0, 2, 0, 0, 1]
>>> C = #Some operations
>>> C
[6, 8, 6, 6, 7]

我当然可以这样解决:

>>> C = []
>>> for val in B:
>>>     C.append(A[val])

但是实际上我被认为是一种更好的方法.特别是因为我想将其用作另一个函数的参数.看起来像A[B]的表达式(但有效)是理想的.我不介意使用NumPy或Pandas解决方案.

But I was actually expected a nicer way to do it. Especially because I want to use it as an argument of another function. An expression looking like A[B] (but a working one) would be ideal. I don't mind solution using NumPy or pandas.

推荐答案

用于获取多个项目 operator.itemgetter 派上用场了:

For fetching multiple items operator.itemgetter comes in handy:

from operator import itemgetter
A = [6, 7, 8]
B = [0, 2, 0, 0, 1]

itemgetter(*B)(A)
# (6, 8, 6, 6, 7)


也正如您提到的numpy一样,可以直接按指定的索引数组来完成此操作,即A[B]:


Also as you've mentioned numpy, this could be done directly by indexing the array as you've specified, i.e. A[B]:

import numpy as np
A = np.array([6, 7, 8])
B = np.array([0, 2, 0, 0, 1])

A[B]
# array([6, 8, 6, 6, 7])

另一种选择是使用 :

np.take(A,B)
# array([6, 8, 6, 6, 7])

这篇关于替换索引数组中与另一个数组对应的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆