Home > Back-end >  replace the values of an np array with its correspondent name
replace the values of an np array with its correspondent name

Time:01-16

I have list with names and their correspondent number. Is there any easy way to replace the correspondent number in a n array back with the correct name? here is an example thanks!

list =[{'Nikolas', 'Kate', 'George'}, [0, 1, 2 ]]

np_array_1 = np.array([1, 2])
np_array_2= np.array([0])
etc.

I mean in a for loop or something, as I have plenty of arrays.

So I would like to get:

np_array_1 = ['Kate', 'George']
np_array_2= ['Nikolas']

CodePudding user response:

Instead of set(set will not maintain order) make a nested list like:

lst =[['Nikolas', 'Kate', 'George'], [0, 1, 2 ]]

make a dictionary to store name and numbers:

d=dict(zip(lst[1],lst[0]))  # here 0 index in lst will have all the numbers and 1 index in lst will have all the names

print(d)
#{0: 'Nikolas', 1: 'Kate', 2: 'George'}

Now, if you want o replace numbers with names you can do:

suppose there is a list with numbers and y want to replace them with names

l=[1,0,2]
e=[]
for x in l: 
    e.append(d[x])

print(e)
#['Kate', 'Nikolas', 'George']
  • Related