gabrielvie

3/29/2018 - 9:40 PM

```
import numpy as np
# Create the following rank 2 array with shape (3, 4).
a = np.array([[1, 3, 5, 7],
[2, 4, 6, 8],
[9, 10, 11, 12]])
# Get all columns in the second row.
row_r1 = a[1, :] # [2 4 6 8] (4,)
# Get all columns from second until third row.
row_r2 = a[1:3, :] # [[2 4 6 8]] (2, 4)
# Get the second colunm of all rows
col_r1 = a[:, 1] # [3 4 10] (3,)
# Get from second until third column of all rows
col_r2 = a[:, 1:3] # [[ 3 5]
# [ 4 6]
# [10 11]] (3, 2)
```

```
import numpy as np
a = np.array([[1, 3, 5, 7],
[2, 4, 6, 8],
[9, 10, 11, 12]])
# Find the odd numbers.
a[(a % 2 != 0)] # [1 3 5 7 9 11]
```

```
import numpy as np
# Create the following rank 2 array with shape (3, 4).
a = np.array([[1, 3, 5, 7],
[2, 4, 6, 8],
[9, 10, 11, 12]])
# Use slicing to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2
# b is the following array of shape (2, 2)
b = a[:2, 1:3] # [[3, 5],
# [4, 6]]
# A slice of an array is a view into the same data, so modifying it
# will modify the original array.
a[0, 1] # "5"
# b[0, 0] is the same piece of data as a[0, 1]
b[0, 0] = 123 # "123"
```

```
import numpy as np
a = np.array([1, 3, 5]) # Create a rank 1 array
type(a) # <class 'numpy.ndarray'>
a.shape # (3,)
b = np.array([[1, 3, 5],
[2, 4, 6]]) # Create a rank 2 array
b.shape # (2, 3) Two lines and 3 columns
c = np.array((2, 2)) # Create an array of all zeros
# [[0. 0.],
# [0. 0.]]
```