Title: Indexing And Slicing Numpy Arrays
Slug: numpy_indexing_and_slicing
Summary: Indexing And Slicing Numpy Arrays
Date: 2016-05-01 12:00
Category: Python
Tags: Basics
Authors: Chris Albon


In [1]:
# Import modules
import numpy as np

In [2]:
# Create a 2x2 array
battle_deaths = [[344, 2345], [253, 4345]]
deaths = np.array(battle_deaths)
deaths


Out[2]:
array([[ 344, 2345],
       [ 253, 4345]])

In [3]:
# Select the top row, second item
deaths[0, 1]


Out[3]:
2345

In [4]:
# Select the second column
deaths[:, 1]


Out[4]:
array([2345, 4345])

In [5]:
# Select the second row
deaths[1, :]


Out[5]:
array([ 253, 4345])

In [6]:
# Create an array of civilian deaths
civilian_deaths = np.array([4352, 233, 3245, 256, 2394])
civilian_deaths


Out[6]:
array([4352,  233, 3245,  256, 2394])

In [7]:
# Find the index of battles with less than 500 deaths
few_civ_deaths = np.where(civilian_deaths < 500)
few_civ_deaths


Out[7]:
(array([1, 3]),)

In [8]:
# Find the number of civilian deaths in battles with less than 500 deaths
civ_deaths = civilian_deaths[few_civ_deaths]
civ_deaths


Out[8]:
array([233, 256])