简体   繁体   中英

How to replace character with a dictionary value in numpy array?

I want to replace characters in a numpy array to specific values in dictionary. For example I want to replace 6837 to fhcg in the same array format.

This is what I tried

import numpy 
val=numpy.array([["6837"],["7628"],["3804"],["3031"],["9848"],["8481"],["1220"],["7701"],["7934"]])
d={'1':'a','2':'b','3':'c','4':'d','5':'e','6':'f','7':'g','8':'h','9':'i','0':'x'}

rep = [d[v] for v in val]
new_val= ' '.join(rep)

But its giving this error

TypeError: unhashable type: 'numpy.ndarray'

I think you want:

rep = []
for v in val:
    st = ''.join(d[ch] for ch in v[0])
    rep.append(st)
new_val= ' '.join(rep)

Or with list comprehension:

rep = [ ''.join(d[ch] for ch in v[0]) for v in val ]

Your val array is 2d, so you have to be careful how you iterate on it.

In [255]: val.shape
Out[255]: (9, 1)

Let's define a little function that converts one string; the conversion is character by character - it's a pure string operation.

def foo(astr):
   return ''.join([d[v] for v in astr])

We could use this in a list comprehension or other iterator. But this is one case where np.vectorize does a nice job.

In [257]: f = np.vectorize(foo)
In [258]: f(val)
Out[258]: 
array([['fhcg'],
       ['gfbh'],
       ['chxd'],
       ['cxca'],
       ['ihdh'],
       ['hdha'],
       ['abbx'],
       ['ggxa'],
       ['gicd']], 
      dtype='<U4')

It does iterate on the array, so doesn't offer much of a speed advantage, but it takes care of 'broadcasting', handling the 2d array without extra work on our part.

new_val = ''
for v in val:
    s = ''.join(d[n] for n in v[0])
    new_val += s + ' '
new_val = new_val.strip(' ')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM