Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy: Replacing values in a recarray

I'm pretty new to numpy, and I'm trying to replace a value in a recarray. So I have this array:

import numpy as np
d = [('1', ''),('4', '5'),('7', '8')]
a = np.array(d, dtype=[('first', 'a5'), ('second', 'a5')])

I would like to do something like this:

ind = a=='' #Replace all blanks
a[ind] = '12345'

but that doesnt work properly. I was able to do this:

col = a['second']
ind = col=='' #Replace all blanks
col[ind] = '54321'
a['second'] = col

Which works, but I would rather have a way to do it over the entire recarray. Anyone have a better solution?

like image 714
reisner Avatar asked May 30 '26 08:05

reisner


1 Answers

The "element-by-element" operations of numpy (with wich you can perform some function on all elements of the array at once without a loop) don't work with recarrays as far as I know. You can only do that with the individual columns.

If you want to use recarrays, I think the easiest solution is to loop the different columns, although you wanted another solution, but you can do it pretty automatic like this:

for fieldname in a.dtype.names:
    ind = a[fieldname] == ''
    a[fieldname][ind] = '54321'

But maybe you should consider if you really need recarrays, and can't just use normal ndarray. Certainly if you have only one data type (as in the example), then the only advantage are the column names.

like image 154
joris Avatar answered Jun 01 '26 22:06

joris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!