简体   繁体   English

如何用 python 中的列表字符串替换 numpy 数组的数字

[英]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.

相关问题 Python - 列表中的字符串到 numpy 数组 - Python - strings in list to numpy array 如何使用Python或bash将两列数组中的数字替换为另一个文件中的相应字符串? - How to substitute numbers in a two column array with corresponding strings in another file using Python or bash? 用列表替换numpy数组中的项目 - Substitute item in numpy array with list 用列表python中的数字替换哈希 - substitute hash with numbers in list python 如何对存储为 Python 列表中的 numpy 数组的数字运行 for 循环 - how to run a for loop over numbers stored as a numpy array in a list in Python 如何用另一个列表中的元素替换 numpy 数组中的 NaN - How to substitute NaNs in a numpy array with elements in another list 如何使用python用列表中的几个数字替换文本文件中的字符串? - How to substitute string in a text file with a couple of numbers in a list using python? 将 numpy 字符串数组连接到 numpy 数字数组 - Concatenate a numpy array of strings to numpy array of numbers Python列表(字符串)与numpy数组(字符串)中的字符串串联 - String concatenation in Python list (of strings) vs. numpy array (of strings) 如何将字符串列表转换为数字numpy数组? - How to convert a list of strings into a numeric numpy array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM