# Intro to Numpy

Last updated: March 27th, 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)

### Basic Numpy Arrays¶

In [ ]:
np.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[0], a[1]
In [ ]:
a[0:]
In [ ]:
a[1:3]
In [ ]:
a[1:-1]
In [ ]:
a[::2]
In [ ]:
b[0], b[2], b[-1]
In [ ]:
b[[0, 2, -1]]

### Array Types¶

In [ ]:
a
In [ ]:
a.dtype
In [ ]:
b
In [ ]:
b.dtype
In [ ]:
np.array([1, 2, 3, 4], dtype=np.float)
In [ ]:
c = np.array(['a', 'b', 'c'])
In [ ]:
c.dtype
In [ ]:
d = np.array([{'a': 1}, sys])
In [ ]:
d.dtype

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

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
In [ ]:
C.shape
In [ ]:
C.size
In [ ]:
type(C[0])

### Indexing and Slicing of Matrices¶

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