gpt4 book ai didi

python - 如何将数组中的值替换为 Python 中列表中的值?

转载 作者:太空宇宙 更新时间:2023-11-04 00:53:11 25 4
gpt4 key购买 nike

我有一个像这样的数组(numpy.ndarray 类型)

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

和值列表:

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

我想用列表 values 中的项目替换数组 arr 中的数字,使用数组的项目作为列表值的索引:arr[0,0 ]=值[arr[0,0]]

这是我想要的例子

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

有什么优雅的 pythonic 方法可以做到这一点吗?

感谢您提前提供帮助 =)

最佳答案

您可以将 values 转换为 numpy 数组,然后使用简单的索引:

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

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

关于python - 如何将数组中的值替换为 Python 中列表中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36217205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com