 # Intro to NumPy

Last updated: October 31st, 2019  # Intro to Numpy¶

NumPy (Numerical Python) is one of the core packages for numerical computing in Python. Pandas, Matplotlib, Statmodels and many other Scientific libraries rely on NumPy.

NumPy major contributions are:

• Efficient numeric computation with C primitives
• Efficient collections with vectorized operations
• An integrated and natural Linear Algebra API
• A C API for connecting NumPy with libraries written in C, C++, or FORTRAN.

Let's develop on efficiency. In Python, everything is an object, which means that even simple ints are also objects, with all the required machinery to make object work. We call them "Boxed Ints". In contrast, NumPy uses primitive numeric types (floats, ints) which makes storing and computation efficient.  ## Hands on!¶

In :
x = 4

In :
import sys
import numpy as np

In :
np.random.randn(2, 4)

Out:
array([[ 0.59439245, -0.86579428,  0.54393261, -0.79801853],
[ 0.31475968,  0.64303156, -0.52018132, -0.2025787 ]])

### Basic Numpy Arrays¶

In :
np.array([1, 2, 3, 4])

Out:
array([1, 2, 3, 4])
In :
a = np.array([1, 2, 3, 4])

In :
b = np.array([0, .5, 1, 1.5, 2])

In :
a, a

Out:
(1, 2)
In :
a[0:]

Out:
array([1, 2, 3, 4])
In :
a[1:3]

Out:
array([2, 3])
In :
a[1:-1]

Out:
array([2, 3])
In :
a[::2]

Out:
array([1, 3])
In :
b, b, b[-1]

Out:
(0.0, 1.0, 2.0)
In :
b[[0, 2, -1]]

Out:
array([0., 1., 2.]) ### Array Types¶

In :
a

Out:
array([1, 2, 3, 4])
In :
a.dtype

Out:
dtype('int64')
In :
b

Out:
array([0. , 0.5, 1. , 1.5, 2. ])
In :
b.dtype

Out:
dtype('float64')
In :
np.array([1, 2, 3, 4], dtype=np.float)

Out:
array([1., 2., 3., 4.])
In :
c = np.array(['a', 'b', 'c'])

In :
c.dtype

Out:
dtype('<U1')
In :
d = np.array([{'a': 1}, sys])

In :
d.dtype

Out:
dtype('O') In :
A = np.array([
[1, 2, 3],
[4, 5, 6]
])

In :
A.shape

Out:
(2, 3)
In :
A.ndim

Out:
2
In :
A.size

Out:
6
In :
B = np.array([
[
[12, 11, 10],
[9, 8, 7],
],
[
[6, 5, 4],
[3, 2, 1]
]
])

In :
B

Out:
array([[[12, 11, 10],
[ 9,  8,  7]],

[[ 6,  5,  4],
[ 3,  2,  1]]])
In :
B.shape

Out:
(2, 2, 3)
In :
B.ndim

Out:
3
In :
B.size

Out:
12

If the shape isn't consistent, it'll just fall back to regular Python objects:

In :
C = np.array([
[
[12, 11, 10],
[9, 8, 7],
],
[
[6, 5, 4]
]
])

In :
C.dtype

Out:
dtype('O')
In :
C.shape

Out:
(2,)
In :
C.size

Out:
2
In :
type(C)

Out:
list ### Indexing and Slicing of Matrices¶

In :
# Square matrix
A = np.array([
[1, 2, 3],
[4, 5, 6],  # 1
[7, 8, 9]   # 2
])

In :
A

Out:
array([4, 5, 6])
In :
A

Out:
4
In :
A[1, 0]

Out:
4
In :
A[0:2]

Out:
array([[1, 2, 3],
[4, 5, 6]])
In :
A[:, :2]

Out:
array([[1, 2],
[4, 5],
[7, 8]])
In :
A[:2, :2]

Out:
array([[1, 2],
[4, 5]])
In :
A[:2, 2:]

Out:
array([,
])
In :
A

Out:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In :
A = np.array([10, 10, 10])

In :
A

Out:
array([[ 1,  2,  3],
[10, 10, 10],
[ 7,  8,  9]])
In :
A = 99

In :
A

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