Reputation: 437
I'm using python 3.6 .I have a numpy array let's say a.It's in this format
array(['0', '1', '2', ..., '3304686', '3304687', '3304688'],
dtype='<U7')
I have another dictionary b={1: '012', 2: '023', 3: '045',.....3304688:'01288'}
I want to retrieve each value of b and store it in another numpy array by providing the value of a as a key to b. I was planning to try in this way
z_array = np.array([])
for i in range(a.shape[0]):
z=b[i]
z_array=np.append(z_array,z)
But looking the shape of a,I'm feeling that it will be very much time consuming. Can you please suggest me some alternate approach which will be time efficient?
Upvotes: 0
Views: 670
Reputation: 53089
You could use np.frompyfunc
, note that this will create an object array.
b = {str(i): i**3 for i in range(10**7)}
a = [str(i) for i in range(10**7)]
c = np.frompyfunc(b.__getitem__, 1, 1)(a)
or
c = np.frompyfunc(b.get, 1, 1)(a)
to indicate missing keys by None
.
In the example with 10,000,000 items and as many lookups takes just a second or two. (Creating a
and b
takes longer)
Upvotes: 1