Created
February 15, 2016 03:52
-
-
Save aravindhebbali/bcf13d252e112ac4c247 to your computer and use it in GitHub Desktop.
NumPy Arrays: Selecting Array Elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
# select array elements | |
np1 = np.arange(0, 10) | |
np1 | |
# select 3rd and 5th elements | |
np1[2] | |
np1[4] | |
# two dimensional array | |
a2 = np.arange(0, 12).reshape(3, 4) | |
a2 | |
# retrieve element in 1st row/2nd column | |
a2[0, 1] | |
# retrieve element in 3rd row/4th column | |
a2[2, 3] | |
# retrieve second row | |
a2[1,] | |
# retrieve third column | |
a2[:, 2] | |
# logical expressions | |
np1 = np.arange(0, 10) | |
np1 < 4 | |
# complex expressions | |
(np1 < 4) | (np1 > 7) | |
# specify expressions within [] operator | |
np1[np1 < 4] | |
# complex expression | |
np1[(np1 < 4) | (np1 > 7)] | |
# slicing arrays | |
np1 = np.arange(0, 10) | |
np1 | |
# retieve elements from 3 to 7 | |
np1[2:7] | |
# retrieve all elements from 3rd position | |
np1[2:] | |
# retrieve all elements upto 6th position | |
np1[:6] | |
# skip every third element | |
np1[::3] | |
# select element 2 throuugh 8 while skipping every second element | |
np1[1:9:2] | |
# retrieve data in reverse order | |
np1[::-1] | |
# retrieve element 8 through 2 while skipping every second element in reverse | |
np1[8:2:-2] | |
# two dimensional array | |
np2 = np.arange(0, 12).reshape(3, 4) | |
np2 | |
# retrieve columns 1 and 2 | |
np2[:, 1:3] | |
# retrieve rows 2 and 3 | |
np2[1:3,:] | |
# retrieve rows 2 and 3 and columns 3 and 4 | |
np2[1:3, 2:4] | |
# select non-contiguous rows: rows 1 and 3 | |
np2[[0, 2], :] | |
# select non-contiguous columns: columns 2 and 4 | |
np2[:, [1, 3]] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment