1

I have a numpy array and want to replace its values with some strings. 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. 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.). 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? I do appreciate any help in advance.

3
  • 2
    subs_arr = np.array(names)[(numbers-1).astype(np.int)] where numbers should start with 0 since a python index start with 0. However this solution is the same as the one suggested in your link, so I'm voting to close this question. Commented Jun 2, 2021 at 8:22
  • 1
    Does this answer your question? Replace values of a numpy array by values from another numpy array Commented Jun 2, 2021 at 8:25
  • Dear @obchardon, thanks for your help. Honestly, after reading that solution I still could not figure out my problem. Commented Jun 2, 2021 at 8:29

1 Answer 1

2

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:

subs_arr = 
[['base' 'top' 'middle' 'middle']
 ['top' 'middle' 'base' 'top']]
Sign up to request clarification or add additional context in comments.

2 Comments

Dear @yan ziselman, maybe replacing 1 with np.min(numbers) works better, isnt it?
that would depend on the use case and how you form the array 'numbers'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.