-
Notifications
You must be signed in to change notification settings - Fork 1
/
where_2d.Rmd
119 lines (84 loc) · 2.42 KB
/
where_2d.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
---
jupyter:
jupytext:
notebook_metadata_filter: all,-language_info
split_at_heading: true
text_representation:
extension: .Rmd
format_name: rmarkdown
format_version: '1.2'
jupytext_version: 1.6.0
kernelspec:
display_name: Python 3
language: python
name: python3
---
# Where in 2D
This follows from [where and argmin](where_and_argmin).
That page covers how `np.where` and `np.argmin` work for one-dimensional
arrays.
This page covers what happens for `np.where` with arrays of two dimensions and
more.
## Arrays can have two dimensions
```{python}
import numpy as np
```
So far we have only seen one-dimensional arrays.
A *vector* is another term for a one-dimensional array.
Here's a one-dimensional array (vector):
```{python}
arr_one_d = np.array([2, 99, -1, 4, 99])
arr_one_d
```
Notice the `shape` of the array:
```{python}
arr_one_d.shape
```
You can also think of this one-dimensional array as a single *row*.
In fact you can have arrays with more than one row, like this:
```{python}
arr_two_d = np.array([[1, 2, 3, -2, -3], [10, 11, 12, -3, -13]])
arr_two_d
```
Notice the `shape`. This array has 2 rows, each with 5 columns.
```{python}
arr_two_d.shape
```
Remember, we can ask for a single element from a one-dimensional array, using *indexing* with an integer between square brackets. The integer gives the *position* (or offset) of the element we want.
```{python}
arr_one_d[1]
```
With a two-dimensional array, we need to specify the row *and* column of the element we want:
```{python}
arr_two_d[1, 4]
```
The first value between the brackets is the row position, and the second is the column position.
## Revision - using where on one-dimensional arrays
`np.where` gets the indices of the True values in a Boolean array.
```{python}
# A Boolean array.
equal_to_99 = arr_one_d == 99
equal_to_99
```
```{python}
# Indices of the True values.
indices = np.where(equal_to_99)
indices
```
We can use the returned `indices` to index into the array, using square brackets.
```{python}
arr_one_d[indices]
```
## The two-dimensional case
This also works in two or more dimensions.
`np.where` now returns two index arrays, one for the rows, and one for the
columns.
```{python}
indices2d = np.where(arr_two_d == -3)
indices2d
```
Just as for the one-dimensional case, we can use the returned indices to index
into the array, and get the elements.
```{python}
arr_two_d[indices2d]
```