Cheatsheets / Introduction to NumPy
Learn NumPy: Introduction
Indexing NumPy elements using conditionals
NumPy elements can be indexed using conditionals. numbers = [Link]([-5, 4, 0, 2, 3])
The syntax to filter an array using a conditional is
positives = numbers[numbers > 0]
array_name[conditional] .
The returned array will contain only the elements for print(positives)
which the conditional evaluates to True . # array([4, 2, 3])
NumPy element-wise logical operations
NumPy Arrays support element-wise logical operations, numbers = [Link]([-5, 4, 0, 2, 3])
returning new Arrays populated with False or
is_positive = numbers > 0
True based on their evaluation.
print(is_positive)
# array([False, True, False, True, True],
dtype=bool)
Creating NumPy Arrays from files
NumPy Arrays can be created from data in CSV files or imported_csv =
other delimited text by using the
[Link]("[Link]",
[Link]() method.
The named parameter delimiter is used to delimiter=",")
determine the delimiting character between values.
NumPy Arrays
NumPy (short for “Numerical Python”) is a Python # Import the NumPy module, aliased as
module used for numerical computing, creating arrays
'np'
and matrices, and performing very fast operations on
those data structures. The core of NumPy is a import numpy as np
multidimensional Array object.
The NumPy .array() method is used to create
# NumPy Arrays can be created with a list
new NumPy Arrays.
my_array = [Link]([1, 2, 3, 4])
Accessing NumPy Array elements by index
Individual NumPy Array elements can be accessed by matrix = [Link]([[1, 2, 3],
index, using syntax identical to Python lists:
[4, 5, 6],
array[index] for a single element, or
array[start:end] for a slice, where start [7, 8, 9]])
and end are the starting and ending indexes for the
slice. print(matrix[0, 0])
Nested Arrays or elements can be accessed by adding
# 1
additional comma-separated parameters.
print(matrix[1,:])
# array([4, 5, 6])
NumPy element-wise arithmetic operations
NumPy Arrays support element-wise operations, odds = [Link]([1, 3, 5, 7, 9])
meaning that arithmetic operations on arrays are
evens = odds + 1
applied to each value in the array.
Multiple arrays can also be used in arithmetic print(evens)
operations, provided that they have the same lengths. # array([2, 4, 6, 8, 10])
array1 = [Link]([1, 2, 3])
array2 = [Link]([4, 3, 2])
new_array = array1 + array2
print(new_array)
# array([5, 5, 5])
Print Share