Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: Difference between a[i][j] and a[i,j]

Tags:

python

list

numpy

Coming from a Lists background in Python and that of programming languages like C++/Java, one is used to the notation of extracting elements using a[i][j] approach. But in NumPy, one usually does a[i,j]. Both of these would return the same result.

What is the fundamental difference between the two and which should be preferred?

like image 496
Nipun Batra Avatar asked May 12 '13 07:05

Nipun Batra


People also ask

What is difference between array and NumPy array?

NumPy arrays have a fixed size at creation, unlike Python lists (which can grow dynamically). Changing the size of an ndarray will create a new array and delete the original. The elements in a NumPy array are all required to be of the same data type, and thus will be the same size in memory.

How do I count the number of rows in a NumPy array?

In the NumPy with the help of shape() function, we can find the number of rows and columns. In this function, we pass a matrix and it will return row and column number of the matrix. Return: The number of rows and columns.

Why is NumPy so fast?

NumPy is fast because it can do all its calculations without calling back into Python. Since this function involves looping in Python, we lose all the performance benefits of using NumPy. For a 10,000,000-entry NumPy array, this functions takes 2.5 seconds to run on my computer.

What is a correct syntax to create a NumPy array?

The array object in NumPy is called ndarray . We can create a NumPy ndarray object by using the array() function.


1 Answers

The main difference is that a[i][j] first creates a view onto a[i] and then indexes into that view. On the other hand, a[i,j] indexes directly into a, making it faster:

In [9]: a = np.random.rand(1000,1000)

In [10]: %timeit a[123][456]
1000000 loops, best of 3: 586 ns per loop

In [11]: %timeit a[123,456]
1000000 loops, best of 3: 234 ns per loop

For this reason, I'd prefer the latter.

like image 162
NPE Avatar answered Sep 28 '22 10:09

NPE