Convert a string column in a NumPy record array to uppercase

424 Views Asked by At

I create a numpy record array (recarray) as follows:

import numpy as np
recs = [('Bill', '31', 260.0), ('Fred', 15, '145.0')]
r = np.rec.fromrecords(recs, names = 'name, age, weight')

Now I want to alter the column r['name'] so that the values are in uppercase. How do I achieve this?

1

There are 1 best solutions below

7
NaN On BEST ANSWER
recs = [('Bill', '31', 260.0), ('Fred', 15, '145.0')]
r = np.rec.fromrecords(recs, names = 'name, age, weight')
r['name'] = np.char.upper(r['name'])
r
rec.array([('BILL', '31', '260.0'), ('FRED', '15', '145.0')],
          dtype=[('name', '<U4'), ('age', '<U2'), ('weight', '<U32')])

np.char is what you are looking for.