Intro to Numpy
Files associated with this lesson:
Lecture.ipynb
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 [1]:
x = 4
In [2]:
import sys
import numpy as np
In [3]:
np.random.randn(2, 4)
Out[3]:
Basic Numpy Arrays¶
In [4]:
np.array([1, 2, 3, 4])
Out[4]:
In [5]:
a = np.array([1, 2, 3, 4])
In [6]:
b = np.array([0, .5, 1, 1.5, 2])
In [7]:
a[0], a[1]
Out[7]:
In [8]:
a[0:]
Out[8]:
In [9]:
a[1:3]
Out[9]:
In [10]:
a[1:-1]
Out[10]:
In [11]:
a[::2]
Out[11]:
In [12]:
b[0], b[2], b[-1]
Out[12]:
In [13]:
b[[0, 2, -1]]
Out[13]:
Array Types¶
In [14]:
a
Out[14]:
In [15]:
a.dtype
Out[15]:
In [16]:
b
Out[16]:
In [17]:
b.dtype
Out[17]:
In [18]:
np.array([1, 2, 3, 4], dtype=np.float)
Out[18]:
In [19]:
c = np.array(['a', 'b', 'c'])
In [20]:
c.dtype
Out[20]:
In [21]:
d = np.array([{'a': 1}, sys])
In [22]:
d.dtype
Out[22]:
In [23]:
A = np.array([
[1, 2, 3],
[4, 5, 6]
])
In [24]:
A.shape
Out[24]:
In [25]:
A.ndim
Out[25]:
In [26]:
A.size
Out[26]:
In [27]:
B = np.array([
[
[12, 11, 10],
[9, 8, 7],
],
[
[6, 5, 4],
[3, 2, 1]
]
])
In [28]:
B
Out[28]:
In [29]:
B.shape
Out[29]:
In [30]:
B.ndim
Out[30]:
In [31]:
B.size
Out[31]:
If the shape isn't consistent, it'll just fall back to regular Python objects:
In [32]:
C = np.array([
[
[12, 11, 10],
[9, 8, 7],
],
[
[6, 5, 4]
]
])
In [33]:
C.dtype
Out[33]:
In [34]:
C.shape
Out[34]:
In [35]:
C.size
Out[35]:
In [36]:
type(C[0])
Out[36]:
Indexing and Slicing of Matrices¶
In [37]:
# Square matrix
A = np.array([
[1, 2, 3],
[4, 5, 6], # 1
[7, 8, 9] # 2
])
In [38]:
A[1]
Out[38]:
In [39]:
A[1][0]
Out[39]:
In [40]:
A[1, 0]
Out[40]:
In [41]:
A[0:2]
Out[41]:
In [42]:
A[:, :2]
Out[42]:
In [43]:
A[:2, :2]
Out[43]:
In [44]:
A[:2, 2:]
Out[44]:
In [45]:
A
Out[45]:
In [46]:
A[1] = np.array([10, 10, 10])
In [47]:
A
Out[47]:
In [48]:
A[2] = 99
In [49]:
A
Out[49]: