在Python中,如何将数组中的值替换为列表中的值?
我有一个数组(numpy.ndarray类型)如下 以及一个值列表:在Python中,如何将数组中的值替换为列表中的值?,python,arrays,numpy,indexing,Python,Arrays,Numpy,Indexing,我有一个数组(numpy.ndarray类型)如下 以及一个值列表: values=['father','mother','sister','brother','aunt','uncle'] 我想用列表中的项目替换数组中的数字:arr[0,0]=values[arr[0,0]] 这是我想要的一个例子 arr=array([['mother', 'uncle', 'mother'], ['aunt', 'sister', 'father']]) 有什么优雅的蟒蛇式方法可以
values=['father','mother','sister','brother','aunt','uncle']
我想用列表中的项目替换数组中的数字:arr[0,0]=values[arr[0,0]]
这是我想要的一个例子
arr=array([['mother', 'uncle', 'mother'],
['aunt', 'sister', 'father']])
有什么优雅的蟒蛇式方法可以做到这一点吗
感谢您的提前帮助=)您可以将
值转换为numpy数组,然后使用简单的索引:
>>> values = np.array(values)
>>>
>>> values[arr]
array([['mother', 'uncle', 'mother'],
['aunt', 'sister', 'father']],
dtype='|S7')
阅读有关索引的更多信息:使用numpy函数:
In [64]: np.take(values,arr)
Out[64]:
array([['mother', 'uncle', 'mother'],
['aunt', 'sister', 'father']],
dtype='<U7')
[64]中的:np.take(值,arr)
出[64]:
数组([['母亲','叔叔','母亲'],
[“阿姨”、“姐姐”、“父亲”],
dtype='1
In [64]: np.take(values,arr)
Out[64]:
array([['mother', 'uncle', 'mother'],
['aunt', 'sister', 'father']],
dtype='<U7')