简体   繁体   English

如何在Python中将值从数组替换为列表中的值?

[英]How to substitute values from array to values in list in Python?

I have an array (of numpy.ndarray type) like 我有一个(numpy.ndarray类型)的数组

arr=array([[1, 5, 1],
          [4, 2, 0]])

and a list of values: 以及值列表:

values=['father','mother','sister','brother','aunt','uncle']

And I'd like to substitute numbers in array arr with items from list values using array's items as indices of list values: arr[0,0]=values[arr[0,0]] 我想在代数字阵列ARR使用数组的项目作为表值的指数从列表中的值项: arr[0,0]=values[arr[0,0]]

Here an example of what I'd like to have 这是我想要的一个例子

arr=array([['mother', 'uncle', 'mother'],
           ['aunt', 'sister', 'father']])

Is there any elegant pythonic way to do this? 有没有任何优雅的pythonic方式可以做到这一点?

Thanks for helping in advance =) 感谢您的提前帮助=)

You can convert the values to a numpy array then use a simple indexing: 您可以将values转换为numpy数组,然后使用简单的索引:

>>> values = np.array(values)
>>> 
>>> values[arr]
array([['mother', 'uncle', 'mother'],
       ['aunt', 'sister', 'father']], 
      dtype='|S7')

Read more about indexing : http://docs.scipy.org/doc/numpy-1.10.0/reference/arrays.indexing.html 阅读有关索引的更多信息: http : //docs.scipy.org/doc/numpy-1.10.0/reference/arrays.indexing.html

use the numpy take function : 使用numpy take函数:

In [64]: np.take(values,arr)
Out[64]: 
array([['mother', 'uncle', 'mother'],
       ['aunt', 'sister', 'father']], 
      dtype='<U7')

The conversion is then automatic. 转换是自动的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM