[英]How to substitute numbers of a numpy array with strings of a list in python
I have a numpy array and want to replace its values with some strings.我有一个 numpy 数组,想用一些字符串替换它的值。 I checked this solution but could not solve my issue.
我检查了这个解决方案,但无法解决我的问题。 My strings are in a list:
我的字符串在一个列表中:
names=['base', 'middle', 'top']
my list has three strings and it means I have also three numbers in my array:我的列表有三个字符串,这意味着我的数组中也有三个数字:
import numpy as np
numbers=np.array([[3., 1., 2., 2.], [1., 2., 3., 1.]])
To map names with numbers I have this logic: from the first name until the last, numbers decrease.对于带有数字的 map 名称,我有这样的逻辑:从第一个名字到最后一个名字,数字会减少。 I mean first name matches the highest number (
'base': 3.
), next name the second highest ( 'middle': 2.
) and last name equals the lowest ( 'top': 1.
).我的意思是名字匹配最高的数字(
'base': 3.
),第二大的名字( 'middle': 2.
)和姓氏等于最低的数字( 'top': 1.
)。 Finally I want to have my array as:最后我想让我的数组为:
subs_arr= np.array([['base', 'top', 'middle', 'middle'], ['top', 'middle', 'base', 'top']])
Is ther any way to do it automatically (without the need for mapping names with numbers) in python?有什么方法可以在 python 中自动执行(无需将名称与数字映射)? I do appreciate any help in advance.
我非常感谢您提前提供的任何帮助。
How about smth like this:像这样的东西怎么样:
import numpy as np
numbers = np.array([[3., 1., 2., 2.], [1., 2., 3., 1.]]).astype(int)-1
names = np.array(['top', 'middle', 'base'])
subs_arr = names[numbers]
output: output:
subs_arr =
[['base' 'top' 'middle' 'middle']
['top' 'middle' 'base' 'top']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.