将 NumPy 记录数组中的字符串列转换为大写

Convert a string column in a NumPy record array to uppercase

我创建了一个 numpy 记录数组(recarray)如下:

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

现在我想更改 r['name'] 列,使值变为大写。我该如何实现?

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 就是您要找的。