Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get numpy array values? [duplicate]

I have a numpy array like this:

nparray = array([1.])

How can I get the '1'?

Thanks!

like image 668
williamfaith Avatar asked Jun 13 '26 05:06

williamfaith


2 Answers

In [7]: np.array([1.0])                                                                        
Out[7]: array([1.])

For a single item array:

In [8]: np.array([1.0]).item()                                                                 
Out[8]: 1.0

In [9]: np.array([1.0]).tolist()                                                               
Out[9]: [1.0]

For a single item 1d array:

In [10]: np.array([1.0])[0]                                                                    
Out[10]: 1.0

Note that the type of the selection differs with the method. Often that doesn't matter.

In [11]: type(Out[10])                                                                         
Out[11]: numpy.float64
In [12]: type(Out[8])                                                                          
Out[12]: float
In [13]: type(Out[9][0])                                                                       
Out[13]: float

If the array is 0d, item is best

In [14]: np.array(1.0).item()                                                                  
Out[14]: 1.0
In [15]: np.array(1.0)[0]                                                                      
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-15-23b6eb4e1c33> in <module>
----> 1 np.array(1.0)[0]

IndexError: too many indices for array
In [16]: np.array(1.0)[()]                                                                     
Out[16]: 1.0

To get an integer, instead of a float, you have to do an int conversion at some point, either in the array (with astype) or after.

like image 61
hpaulj Avatar answered Jun 14 '26 17:06

hpaulj


int(nparray[0]) hope it helps!

like image 34
Priceless words Avatar answered Jun 14 '26 19:06

Priceless words



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!