Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the time complexity of indexing a numpy array directly

I assume when having a numpy array, let's say

>>>>nArray
array([[  23425.     ,  521331.40625],
       [  23465.     ,  521246.03125],
       [  23505.     ,  528602.8125 ],
       [  23545.     ,  531934.75   ],
       [  23585.     ,  534916.375  ],
       [  23865.     ,  527971.1875 ]])

direct indexing must be pretty efficient.

I imagine something like that nArray[0, 1] = 69696420 must be using a hash-table which will give a time complexity close to O(1). Is that right?

update

As both answers noted, there is no hashing involved in indexing a numpy array. Both answers give a clear explanation about how the indexing happens.

update 2

I added a simple benchmarking to prove the validity of the answers

like image 647
LetsPlayYahtzee Avatar asked Feb 18 '16 14:02

LetsPlayYahtzee


People also ask

Is NumPy indexing fast?

Indexing in NumPy is a reasonably fast operation.

Is NumPy indexing slow?

Numpy is fast with operating on vectors (matrices), when performed on the whole structure at once. Such single element-by-element operations are slow.

What is the time complexity to get the element at index i of an array?

Using the index value, we can access the array elements in constant time. So the time complexity is O(1) for accessing an element in the array.

What is the time complexity of index in Python?

The index() method has linear runtime complexity in the number of list elements. For n elements, the runtime complexity is O(n) because in the worst-case you need to iterate over each element in the list to find that the element does not appear in it.


1 Answers

There is no hash table involved. Numpy arrays are arrays, just like the name implies, and the address is computed like this:

address of nArray[x, y] = base address + A * x + B * y
like image 136
Dietrich Epp Avatar answered Oct 11 '22 18:10

Dietrich Epp