Indexing 1D Arrays¶
In [1]:
%pip install numpy
import numpy as np
In [3]:
foo = np.array([10, 20, 30, 40, 50])
print(foo)
[10 20 30 40 50]
In [5]:
foo[0]
Out[5]:
10
In [6]:
foo[1] = 99
In [7]:
print(foo)
[10 99 30 40 50]
In [11]:
foo[-1]
Out[11]:
50
In [12]:
foo[999]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[12], line 1 ----> 1 foo[999] IndexError: index 999 is out of bounds for axis 0 with size 5
In [14]:
foo[[0, 1, 4]]
Out[14]:
array([10, 99, 50])
In [15]:
foo[[0,1,0,1]]
Out[15]:
array([10, 99, 10, 99])
In [20]:
foo[np.zeros(shape=3, dtype='int64')]
Out[20]:
array([10, 10, 10])
In [21]:
foo[:2]
Out[21]:
array([10, 99])
In [22]:
foo[2:]
Out[22]:
array([30, 40, 50])
In [23]:
foo[::2]
Out[23]:
array([10, 30, 50])
In [25]:
foo[[0,1,4]] = [100,200,400]
foo
Out[25]:
array([100, 200, 30, 40, 400])
In [26]:
foo[[0,1,4]] = [1,2]
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[26], line 1 ----> 1 foo[[0,1,4]] = [1,2] ValueError: shape mismatch: value array of shape (2,) could not be broadcast to indexing result of shape (3,)
In [28]:
foo[[0,1,4]] = 1
foo
Out[28]:
array([ 1, 1, 30, 40, 1])