Reputation: 532
I have a very large list of lists containing numpy ndarrays where I need to map letters to an integer value.
This is along the lines of what I was thinking might work, but it doesn't seem to catch all arrays.
import numpy as np
x = [np.array(['a','b','c']),np.array(['d','e']),np.array(['a','e'])]
dict_x = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e':5}
x[ x == 'a'] = dict_x.get('a')
Output: [1, array(['d', 'e'],
dtype='<U1'), array(['a', 'e'],
dtype='<U1')]
I was also trying to iterate through all of the keys to replace them in the array one by one with the following
for i in dict_x.keys():
x[ x == i] = dict_x.get(i)
but this returns, which I suppose makes sense. Anyone have any clever ways to replace all of these values at once and in all instances? Thanks very much!
[5, array(['d', 'e'],
dtype='<U1'), array(['a', 'e'],
dtype='<U1')]
Upvotes: 0
Views: 482
Reputation: 2025
You can try this:
x = [np.array(['a','b','c'], dtype="<U4"),np.array(['d','e'], dtype="<U4"),np.array(['a','e'], dtype="<U4")]
dict_x = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e':5}
for i in x:
i[ i == 'a'] = dict_x.get('a')
x = array(['1', 'b', 'c'],
dtype='<U1'), array(['d', 'e'],
dtype='<U1'), array(['1', 'e'],
dtype='<U1')]
Upvotes: 1