Search code examples
numpynumpy-ndarrayrecarray

Convert a string column in a NumPy record array to uppercase


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?


Solution

  • 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.