3

I have a numpy array like this:

nparray = array([1.])

How can I get the '1'?

Thanks!

1

3 Answers 3

15
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Watch out, does not work with NDArray - gluon.mxnet.io/chapter01_crashcourse/ndarray.html#Watch-out! if you are using their library.
2

int(nparray[0]) hope it helps!

Comments

0

You can get it by passing the index such as

nparray[0]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.