I have a NumPy record array of floats:
import numpy as np
ar = np.array([(238.03, 238.0, 237.0),
(238.02, 238.0, 237.01),
(238.05, 238.01, 237.0)],
dtype=[('A', 'f'), ('B', 'f'), ('C', 'f')])
How can I determine min/max from this record array? My usual attempt of ar.min() fails with:
TypeError: cannot perform reduce with flexible type
I'm not sure how to flatten the values out into a simpler NumPy array.
The easiest and most efficient way is probably to view your array as a simple 2D array of floats:
ar_view = ar.view((ar.dtype[0], len(ar.dtype.names)))
which is a 2D array view on the structured array:
print ar_view.min(axis=0) # Or whatever…
This method is fast, as no new array is created (changes to ar_view result in changes to ar). It is restricted to cases like yours, though, where all record fields have the same type (float32, here).
One advantage is that this method keeps the 2D structure of the original array intact: you can find the minimum in each "column" (axis=0), for instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With