In [1]:
import numpy as np
In [2]:
# 1D array
a = np.array([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97])
In [3]:
print(a.shape) # Return the ``shape`` of the array
print(a)
In [4]:
# 2D array
b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
In [5]:
print(b.shape) # Return the ``shape`` of the array
print(b)
To call or change the element in the array, we can apply similar operation as a list
In [6]:
print(a[0], a[3], a[5])
In [7]:
print(b[0,0],b[1,1],b[2,2])
In [8]:
x = range(100000)
sum(x)
Out[8]:
In [9]:
y = np.array(x)
np.sum(y)
Out[9]:
In [10]:
%timeit sum(x)
In [11]:
%timeit np.sum(y)
In [12]:
# Create an array of all zeros
np.zeros((5, 5))
Out[12]:
In [13]:
# Create an array of all ones
np.ones((5,5))
Out[13]:
In [14]:
# Create a constant array
np.ones((5,5)) * 7
Out[14]:
In [15]:
np.full((5,5), 7)
Out[15]:
In [16]:
# Create a 3x3 identity matrix
np.eye(3)
Out[16]:
In [17]:
# Create an array filled with random values from 0 to 1
np.random.random((3,2))
Out[17]:
In [18]:
# Create an 1D array filled with random integer from 1 to n
np.random.randint(1, 1000, 10)
Out[18]:
In [19]:
# Seeding the random values will always give you the same "random" numbers on next run
# We put the answer to the Ultimate Question of Life, the Universe, and Everything to the seed integer
np.random.seed(42)
In [20]:
# Create an 1D array filled with random integer from 1 to n
np.random.randint(1, 1000, 10)
Out[20]:
In [21]:
### Slicing
In [22]:
e = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
e
Out[22]:
In [23]:
# Each dimensions slice similar to a list, here it means 1st dimension select all,
# 2nd dimension select from one till end.
e[:,1:]
Out[23]:
In [24]:
# Here it means 1st dimension and 2nd dimension select from start till 2,
# i.e. the upper left part of the array.
e[:2,:2]
Out[24]:
In [25]:
# An operation like numpy array > than a value return a boolean array
e > 5
Out[25]:
In [26]:
# If we put the boolean array into the same array, it will select all element that satisfy the conditions
e[e > 5]
Out[26]: