Title: Indexing And Slicing Numpy Arrays
Slug: indexing_and_slicing_numpy_arrays
Summary: Indexing And Slicing Numpy Arrays
Date: 2016-05-01 12:00
Category: Python
Tags: Basics
Authors: Chris Albon
Unlike many other data types, slicing an array into a new variable means that any chances to that new variable are broadcasted to the original variable. Put other way, a slice is a hotlink to the original array variable, not a seperate and independent copy of it.
In [1]:
# Import Modules
import numpy as np
In [2]:
# Create an array of battle casualties from the first to the last battle
battleDeaths = np.array([1245, 2732, 3853, 4824, 5292, 6184, 7282, 81393, 932, 10834])
In [3]:
# Divide the array of battle deaths into start, middle, and end of the war
warStart = battleDeaths[0:3]; print('Death from battles at the start of war:', warStart)
warMiddle = battleDeaths[3:7]; print('Death from battles at the middle of war:', warMiddle)
warEnd = battleDeaths[7:10]; print('Death from battles at the end of war:', warEnd)
In [4]:
# Change the battle death numbers from the first battle
warStart[0] = 11101
In [5]:
# View that change reflected in the warStart slice of the battleDeaths array
warStart
Out[5]:
In [6]:
# View that change reflected in (i.e. "broadcasted to) the original battleDeaths array
battleDeaths
Out[6]:
Note: This multidimensional array behaves like a dataframe or matrix (i.e. columns and rows)
In [7]:
# Create an array of regiment information
regimentNames = ['Nighthawks', 'Sky Warriors', 'Rough Riders', 'New Birds']
regimentNumber = [1, 2, 3, 4]
regimentSize = [1092, 2039, 3011, 4099]
regimentCommander = ['Mitchell', 'Blackthorn', 'Baker', 'Miller']
regiments = np.array([regimentNames, regimentNumber, regimentSize, regimentCommander])
regiments
Out[7]:
In [8]:
# View the first column of the matrix
regiments[:,0]
Out[8]:
In [9]:
# View the second row of the matrix
regiments[1,]
Out[9]:
In [10]:
# View the top-right quarter of the matrix
regiments[:2,2:]
Out[10]: