# numpy: Introduction

Let's import the numpy module.

In :
import numpy as np

In :
n = 10  # CHANGE ME
a1 = list(range(n))
a2 = np.arange(n)

if n <= 10:
print(a1)
print(a2)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0 1 2 3 4 5 6 7 8 9]


In :
%timeit [i**2 for i in a1]

100000 loops, best of 3: 2.36 µs per loop


In :
%timeit a2**2

1000000 loops, best of 3: 1.06 µs per loop



Numpy Arrays: much less flexible, but:

• much faster
• less memory

Ways to create a numpy array:

• Casting from a list
In :
np.array([1,2,3])

Out:
array([1, 2, 3])

• linspace
In :
np.linspace(-1, 1, 10)

Out:
array([-1.        , -0.77777778, -0.55555556, -0.33333333, -0.11111111,
0.11111111,  0.33333333,  0.55555556,  0.77777778,  1.        ])

• zeros
In :
np.zeros((10,10), np.float64)

Out:
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])


Operations on arrays propagate to all elements:

In :
a = np.array([1.2, 3, 4])
b = np.array([0.5, 0, 1])


Addition, multiplication, power, .. are all elementwise:

In :
a+b

Out:
array([ 1.7,  3. ,  5. ])

In :
a*b

Out:
array([ 0.6,  0. ,  4. ])

In :
a**b

Out:
array([ 1.09544512,  1.        ,  4.        ])


Matrix multiplication is np.dot(A, B) for two 2D arrays.

Numpy arrays have two (most) important attributes:

In :
a = np.random.rand(5, 4, 3)
a.shape

Out:
(5, 4, 3)

In :
a.dtype

Out:
dtype('float64')


Other dtypes include np.complex64, np.int32, ...