Using arrays, there are times we only want to use part of an array. Especially in machine learning. Often we need to split the array that contains X and Y values. Typically the X values are the first columns of the array, and the Y value is the final column of the array. Notice that all rows and columns start with 0. Thus a three column array with have rows 0, 1, 2; and columns 0, 1, 2. In a slicing operation we have row, then column; for example array[row,column]. The : in the operation signifies all rows or columns. The slicing action itself occurs just before the location indicated. For example, array[ : , 0:2] includes all rows, and includes column 0 and 1. This saves the first two columns. We will create an array and practice slicing it.
#Practice slicing a 2D array
#Create a 2D array
#Rows and Col start at 0. #2 is designated as location (0,1)
# 1 2 3
# 4 5 6
# 7 8 9
import numpy as np
myArray = np.array([[1,2,3],[4,5,6],[7,8,9]])
print (myArray)
#Output
# [[1 2 3]
# [4 5 6]
# [7 8 9]]
#Slice off the last column
#Save first two columns
#0 is the first column
# the slice occurs on #1
# : indicates all rows or columns
X = myArray[:, 0:2]
print(X)
#Output
# [[1 2]
# [4 5]
# [7 8]]
#Save the last column
Z = myArray[:, 2]
print(Z)
#Output
# [3 6 9]
#Select upper left corner
Y = myArray[0:2, 0:2]
print(Y)
# Output
# [[1 2]
# [4 5]]
Table of Contents
Ch1-Starting Out
Ch2-Loops
Ch3-If Statements
Ch4-Functions
Ch5-Variable Scope
Ch6-Bubble Sort
Ch7-Intro to OOP
Ch8-Inheritance
Ch9-Plotting
Ch10-Files
Ch11-Print Format
Ch12-Dict-Zip-Comp
Ch13-Slice Arrays