Skip to content Skip to sidebar Skip to footer

Min Function In Numpy Array

I am trying to find a min value from one dimensional numpy array which which looks like: col = array(['6.7', '0.9', '1.3', '4', '1.8'],dtype='|S7'), using col.min(), which is no

Solution 1:

The problem is that you have an array of strings, not an array of numbers. You therefore need to convert the array to an appropriate type first:

In [38]: col.astype(np.float64).min()
Out[38]: 0.90000000000000002

should I have specified the data type while reading the values or while using the min function

If you know the input to be numeric, it would make sense to specify the data type when reading the data.

Solution 2:

An alternative is to use the python builtin min function in conjunction with the key keyword:

>>>import numpy as np>>>col = np.asarray(['6.7', '0.9', '1.3', '4', '1.8'])>>>min(col,key=float)
'0.9'

Solution 3:

If you won't need to do many other numerical operations and you have a reason for preferring the data to reside in str format, you can always use the native Python min and max operating on a plain list of your data:

In [98]: col = np.asarray(['6.7', '0.9', '1.3', '4', '1.8'])

In [99]: col
Out[99]:
array(['6.7', '0.9', '1.3', '4', '1.8'],
      dtype='|S3')

In [100]: col.min()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent calllast)
<ipython-input-100-1ce0c6ec1def>in<module>()
----> 1 col.min()

TypeError: cannot perform reduce with flexible type

In [101]: col.tolist()
Out[101]: ['6.7', '0.9', '1.3', '4', '1.8']

In [102]: min(col.tolist())
Out[102]: '0.9'In [103]: max(col.tolist())
Out[103]: '6.7'

In general, this isn't a good way to handle numerical data and could be susceptible to many faulty assumptions about what resides in your array. But it's just another option to consider if you need to or if you have a special reason for working with strings (such as, you're only ever calculating the min and max and all you do with them is display them).

Post a Comment for "Min Function In Numpy Array"