Reputation: 35
if you have an array, and you want to convert it by using your defined dictionary, how do you do? input:
my_dict = {1 : 'J',2:'F', 3:'M',4: 'A',5: 'M',6 : 'J',7:'J', 8:'A',9: 'S',10: '0',11 : 'N',12:'D'}
x=np.array(2,6,8,1,.....)
output:
y=("F","J","A","J",.....)
We have tried this:
my_dict = {1 : 'J',2:'F', 3:'M',4: 'A',5: 'M',6 : 'J',7:'J', 8:'A',9: 'S',10: '0',11 : 'N',12:'D'}
a = np.empty(len(x))
for i in range(0,len(x)):
b=my_dict[x[i,0]]
a[i,0]=b
Upvotes: 1
Views: 70
Reputation: 146
dict.get()
won't throw KeyNotFoundError exception if the key doesn't exist.
my_dict = {1 : 'J',2:'F', 3:'M',4: 'A',5: 'M',6 : 'J',7:'J', 8:'A',9: 'S',10: '0',11 : 'N',12:'D'}
# With KeyNotFoundError handled
x=[my_dict.get(i) for i in [2,6,8,1,10,11]]
Upvotes: 0
Reputation: 146
Dont know why numpy but this code will work:
my_dict = {1 : 'J',2:'F', 3:'M',4: 'A',5: 'M',6 : 'J',7:'J', 8:'A',9: 'S',10: '0',11 : 'N',12:'D'}
x=[2,6,8,1,10,11]
result=[]
for key in x:
result.append(my_dict[key]);
print(result)
Upvotes: 0
Reputation: 53744
Why you are using numpy here is beyond me and please note that your numpy arrange initialization syntax is incorrect. But you said output that looks like
("F","J","A","J",.....)
for that you need something like:
import numpy as np
my_dict = {1 : 'J',2:'F', 3:'M',4: 'A',5: 'M',6 : 'J',7:'J', 8:'A',9: 'S',10: '0',11 : 'N',12:'D'}
x=np.array([2,6,8,1,10,11])
[my_dict[i] for i in x]
Upvotes: 2