CSC 203 chapter 7: Array-Oriented Programming with NumPy

0.0(0)
studied byStudied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/66

encourage image

There's no tags or description

Looks like no tags are added yet.

Last updated 5:20 PM on 12/10/25
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai

No analytics yet

Send a link to your students to track their progress

67 Terms

1
New cards

ndarray

n-dimensional array type

2
New cards

import numpy as np

The NumPy documentation recommends importing the numpy module as np so that you can access its members with "np."

3
New cards

np.array()

array function receives as an argument an array or other collection of elements and returns a new array containing the argument’s elements

4
New cards

The array function

copies its argument’s contents into the array

5
New cards

numpy.ndarray

the type of object that function array returns

Example input: type(array_name)

6
New cards

When outputting an array, how is it formatted?

NumPy separates each value from the next with a comma and a space and right-aligns all the values using the same field width. It determines the field width based on the value that occupies the largest number of character positions

Ex: 

  • numbers = np.array([2, 3, 5, 7, 11])

  • numbers

    array([  2,  3,  5,  7, 11])

7
New cards

Arrays with Multidimensional Arguments

NumPy auto-formats arrays, based on their number of dimensions, aligning the columns within each row.

<p>NumPy auto-formats <span>array</span>s, based on their number of dimensions, aligning the columns within each row.</p>
8
New cards

An array object provides attributes that enable you to

discover information about its structure and contents

9
New cards

NumPy does not display trailing 0s to the

right of the decimal point in floating-point values.

10
New cards

array_name.dtype

returns an array’s data type

11
New cards

int64

Numpy’s default data type for integers

  • 64 corresponds to 64-bit (8-byte) integers

12
New cards

float64

Numpy’s default data type for floats

  • 64 corresponds to 64-bit (8-byte) floating-point values

13
New cards

bool

Boolean data type

14
New cards

object

for non-numeric data (such as strings)

15
New cards

array_name.ndim

returns an integer that tells us how many dimensions (rows) the array has

16
New cards

array_name.shape

returns a tuple specifying an array’s dimensions 

  • (rows, columns)

17
New cards

array_name.size

returns an array’s total number of elements

  • If multidimensional, __ is the product of the array’s shape tuple values

18
New cards

array_name.itemsize

the number of bytes required to store each element

  • 8 if int64 or float64

  • 4 if int32 or float32

19
New cards

Arrays are iterable so you could use

for loops

20
New cards

array_name.flat

You can iterate through a multidimensional array as if it were one-dimensional by using its flat attribute

21
New cards

np.zeros()

creates a new array of specified shapes and types, filled with 0s

  • numpy.zeros((shape), dtype = None)

22
New cards

np.ones()

returns a new array of given shape and type, with 1s

  • numpy.ones((shape), dtype = None)

23
New cards

By default, functions zeros and ones create

arrays containing float64 values.

24
New cards

zeros, ones, full: The first argument to these functions must be

an integer or a tuple of integers specifying the desired dimensions

  • For an integer, each function returns a one-dimensional array with the specified number of elements

  • For a tuple of integers, these functions return a multidimensional array with the specified dimensions

25
New cards

zeros, ones, full: You can specify the array’s element type with the

zeros and ones function’s dtype keyword argument. Optional

  • dtype=

26
New cards

np.full()

Return a new array of given shape and type, filled with fill_value.

  • numpy.full((shape), fill_value, dtype=None)

27
New cards

np.arange(start, stop+1, step) 

creates an array of equally spaced values within a defined interval. Similar to using built-in function range

28
New cards

np.linspace(start, stop, num=_ )

produces evenly spaced floating-point ranges. The function’s first two arguments specify the starting and ending values in the range, and the ending value is included in the array. The optional keyword argument num specifies the number of evenly spaced values to produce—this argument’s default value is 50

29
New cards

array_name.reshape(rows,columns)

transforms an array into different number of dimensions. (rows, columns). New shape must have the same number of elements as the original

30
New cards

Most array operations execute significantly

faster than corresponding list operations.

31
New cards

%timeit

times the average duration of operations

32
New cards

np.random.randint( _ , size=())

generates an array with random integers. Arguments (left to right) include:

  • generate random integers from 0 to _

  • size = how many random integers to generate

33
New cards

NumPy provides many operators which enable you to

write simple expressions that perform operations on entire arrays

34
New cards

Element-wise operations are applied to

every element in an array

35
New cards

Which operators are commutative?

+ and *. This means the order of the expression does not matter

  • 2 * var is the same as var * 2

36
New cards

scalar

one operand that is a single value

37
New cards

broadcasting

allows us to perform arithmetic operations on arrays of different shapes without reshaping them. It automatically adjusts the smaller array to match the larger array's shape by replicating its values along the necessary dimensions

  • When one operand is a scalar, NumPy performs the element-wise calculations as if the scalar were an array of the same shape as the other operand, but with the scalar value in all its elements

<p><span>allows us to perform arithmetic operations on arrays of different shapes without reshaping them. It automatically adjusts the smaller array to match the larger array's shape by replicating its values along the necessary dimensions</span></p><ul><li><p>When one operand is a scalar, NumPy performs the element-wise calculations as if the scalar were an array of the same shape as the other operand, but with the scalar value in all its elements</p></li></ul><p></p>
38
New cards

arithmetic operations require as operands

two arrays of the same size and shape

39
New cards

You may perform arithmetic operations and augmented assignments between

arrays of the same shape. The result is a new array formed by performing an operation on the arrays element-wise in each operand.

  • Arithmetic between arrays of integers and floating-point numbers results in an array of floating-point numbers

40
New cards

You can compare arrays with individual values and with other arrays. Comparisons are performed

element-wise. Such comparisons produce arrays of Boolean values in which each element’s True or False value indicates the comparison result.

  • Broadcasting is used to compare an array with a scalar

<p>element-wise. Such comparisons produce <span>array</span>s of Boolean values in which each element’s <span>True</span> or <span>False</span> value indicates the comparison result. </p><ul><li><p>Broadcasting is used to compare an array with a scalar</p></li></ul><p></p>
41
New cards

Each of the following is a functional-style programming reduction

We can use methods to calculate sum, min, max, mean, std (standard deviation) and var (variance) on an array —

42
New cards

The keyword (axis=_)

refers to specific array dimensions in a two-dimensional array

43
New cards

axis=0

performs the calculation on values within each column. Vertically

44
New cards

axis=1

performs the calculation on values within each row. Horizontally

45
New cards

universal functions (or ufuncs

perform various element-wise operations using one or two array or array-like (such as lists) arguments. Some are called when you use operators like + and * on arrays

46
New cards

np.sqrt(array_name)

a universal function that calculates the square root of an array’s values

47
New cards

np.add(array_1, array_2)

a universal function that adds two arrays with the same shape. It’s equivalent to: array_1 + array_2

48
New cards

np.multiply(array_name, scalar)

Universal function that broadcasts. It multiplies every element of array_name by the scalar value. It’s equivalent to: array_name * scalar

49
New cards

A one-dimensional array with the same length as each row of a two-dimensional array

can be supported by broadcasting

50
New cards

One-dimensional arrays can be indexed and sliced using the same syntax and techniques

that lists and tuples use

51
New cards

To select an element in a two-dimensional array,

specify a tuple containing the element’s row and column indices in [ ]

<p>specify a tuple containing the element’s row and column indices in [ ] </p>
52
New cards

To select a single row from a two-dimensional array,

specify only one index in square brackets

<p>specify only one index in square brackets</p>
53
New cards

To select multiple sequential rows,

use slice notation

<p>use slice notation </p>
54
New cards

To select multiple non-sequential rows,

use a list of row indices separated by ,

<p>use a list of row indices separated by ,</p>
55
New cards

You can select subsets of the columns by providing a tuple specifying

the row(s) and column(s) to select. Each can be a specific index, a slice, or a list.

  • [:,_] a slice representing all rows

  • [_, # :#] select consecutive columns using a slice

  • [_, [#, #]] specific columns using a list of column indices

56
New cards

views

objects that “see” the data in other objects, rather than having their own copies of the data. Also known as a shallow copy

57
New cards

array_name.view()

returns a new array object with a view of the original array object’s data. Modifying a value in the original or view array, changes it in the other

58
New cards

Slices also create

views of the original array

<p>views of the original array</p>
59
New cards

array_name.copy()

returns a new array object with a deep copy of the original array object’s data. Creates a deep copy with independent copies of the original data

60
New cards

array_name.resize(rows,columns)

modifies the original array’s shape

61
New cards

array_name.flatten()

Takes a multidimensional array and flattens it into a single dimension. Deep copies the original array’s data

<p>Takes  a multidimensional array and flattens it into a single dimension. <strong>Deep copies the original array’s data</strong></p>
62
New cards

array_name.ravel()

Takes a multidimensional array and flattens it into a single dimension. Produces a view of the original array, which shares the original array’s data

<p>Takes  a multidimensional array and flattens it into a single dimension. <strong>Produces a view of the original <span>array</span>, which shares the <span>original array</span>’s data</strong></p>
63
New cards

transpose an array’s rows and columns

“flip” the array, so the rows become the columns and the columns become the rows

64
New cards

array_name.T

the T attribute returns a transposed view (shallow copy) of the array. Transposing does not modify the original array

65
New cards

horizontal stacking and vertical stacking does what?

combine arrays by adding more rows or more columns

66
New cards

hstack (horizontal stack) function

np.hstack((array_1, array_2))

pass a tuple containing the arrays to combine. Combines arrays by adding onto the rows

67
New cards

vstack (vertical stack) function

np.vstack((array_1, array_2))

pass a tuple containing the arrays to combine. Places the arrays on top of each other