Title: Selecting Elements In An Array
Slug: selecting_elements_in_an_array
Summary: How to select elements in a NumPy array.
Date: 2017-09-03 12:00
Category: Machine Learning
Tags: Vectors Matrices Arrays
Authors: Chris Albon

Preliminaries


In [1]:
# Load library
import numpy as np

Create Vector


In [2]:
# Create row vector
vector = np.array([1, 2, 3, 4, 5, 6])

Select Element


In [3]:
# Select second element
vector[1]


Out[3]:
2

Create Matrix


In [4]:
# Create matrix
matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

Select Element


In [5]:
# Select second row, second column
matrix[1,1]


Out[5]:
5

Create Tensor


In [6]:
# Create matrix
tensor = np.array([
                    [[[1, 1], [1, 1]], [[2, 2], [2, 2]]],
                    [[[3, 3], [3, 3]], [[4, 4], [4, 4]]]
                  ])

Select Element


In [7]:
# Select second element of each of the three dimensions
tensor[1,1,1]


Out[7]:
array([4, 4])