Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

prefered method to get an element of numpy array

Looking at a numpy array, i find two methods to get an element from the answers given to this question: How to call an element in a numpy array?.

There are the two methods:
a[i][j] or a[i,j]

Here is a minimum reproducable example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import numpy as np
a = np.arange(15).reshape(3, 5)
'''
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
'''


print(a[1][1])  # returns 6
print(a[1,1])   # return 6

Both appear to give the same result, so is one method better than the other ?

>Solution :

a[1][1]

Returns the slice a[1] and then indexes that slice at [1]

a[1] -> array([5, 6, 7, 8, 9])
array([5, 6, 7, 8, 9])[1] -> 6

Whereas

a[1, 1]

Does the same end-result calculation but all within the numpy API in C, so is faster:

a[1][1]
360 ns ± 28.7 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

a[1, 1]
191 ns ± 2.76 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading