0% found this document useful (0 votes)
38 views

Numpy

This document provides an overview of Chapter 3 on the introduction to NumPy in Python. It discusses what NumPy is, how to create NumPy arrays from lists, scratch, and random number generation. It covers NumPy array attributes and basics like indexing, slicing, reshaping, concatenation, and splitting arrays. It also summarizes how to perform computations on arrays using arithmetic operations and broadcasting. Other topics include comparisons and boolean logic, aggregations like minimum, maximum, and averaging values in arrays. The document provides examples throughout.

Uploaded by

Khả Uyên
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Numpy

This document provides an overview of Chapter 3 on the introduction to NumPy in Python. It discusses what NumPy is, how to create NumPy arrays from lists, scratch, and random number generation. It covers NumPy array attributes and basics like indexing, slicing, reshaping, concatenation, and splitting arrays. It also summarizes how to perform computations on arrays using arithmetic operations and broadcasting. Other topics include comparisons and boolean logic, aggregations like minimum, maximum, and averaging values in arrays. The document provides examples throughout.

Uploaded by

Khả Uyên
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Chapter 3: Introduction to NumPy

Lecturer: Nguyen Tuan Long, Phd


Email: [email protected]
Mobile: 0982 746 235
Chapter 3: Introduction to Numpy 2

• What is Numpy?
• Creating Numpy Arrays.
• Basic of Numpy Arrays.
• Computation on NumPy Arrays.
• Aggregations: Min, Max, and Everything in Between.
• Comparisons, Masks, and Boolean Logic.
• Sorting Arrays.
What is Numpy? 3

• Numpy: Numerical Python

• The NumPy library is the core library for scientific computing in


Python.

• It provides a high-performance multidimensional array object, and


tools for working with these arrays.


Creating Numpy Arrays 4

Creating Arrays from Python Lists

Note: Remember that unlike Python lists, NumPy is constrained to arrays


that all contain the same type
Creating Numpy Arrays 5
Creating Numpy Arrays 6

Creating Arrays from Scratch

np.zeros(shape, dtype=float, order =‘C’) np.ones(shape, dtype=None, order =‘C’)


Return a new array of given shape and type, filled Return a new array of given shape and type, filled with
with zeros ones

np.full(shape, fill_value, dtype=None, order='C’)


Return a new array of given shape and type, filled with fill_value.
Creating Numpy Arrays 7

np.arange(start, stop, step, dtype=None):


Return evenly spaced values within a given interval.

np.linspace(start, stop, num=50, endpoint=True, retstep=False,dtype=None, axis=0)


Return evenly spaced numbers over a specified interval.

np.random.random(size=None)
Return random floats in the half-open
interval [0.0, 1.0).
Creating Numpy Arrays 8

np.random.normal(loc=0.0, scale=1.0, size=None)


Draw random samples from a normal (Gaussian) distribution.

np.random.randint(low, high=None, size=None, dtype=int)


Return random integers from low (inclusive) to high (exclusive).
Creating Numpy Arrays 9

Create a identity matrix:

numpy.empty(shape, dtype=float, order='C')


Return a new array of given shape and type, without initializing entries.
Creating Numpy Arrays 10

NumPy Standard Data Types


The Basic of NumPy Arrays 11

NumPy Array Attributes


import numpy as np
np.random.seed(0) # seed for reproducibility
x1 = np.random.randint(10, size=6) # One-dimensional array
x2 = np.random.randint(10, size=(3, 4)) # Two-dimensional array
x3 = np.random.randint(10, size=(3, 4, 5)) # Three-dimensional array

The number of dimensions


The size of each dimension
The total size of the array
The Basic of NumPy Arrays 12

Array Indexing: Accessing Single Elements


• One-dimensional array: • Multidimensional array: using a comma-
the same as a list separated tuple of indices

0
1
2

0 1 2 3

x[row , column]
The first dimensional The second dimensional
The Basic of NumPy Arrays 13

Array Indexing: Accessing Single Elements


• Modify values using the index notation: • Note: NumPy arrays have a fixed type
The Basic of NumPy Arrays 14

Array Slicing: Accessing Subarrays

x[start:stop:step]
• One-dimensional subarrays
The Basic of NumPy Arrays 15

• Multidimensional subarrays

• Accessing array rows and columns


The Basic of NumPy Arrays 16

• Subarrays as no-copy views


Now if we
modify this
subarray

Note:
• One important—and extremely useful—thing to know about array slices is
that they return views rather than copies of the array data. This is one area
in which NumPy array slicing differs from Python list slicing: in lists, slices
will be copies.
• This default behavior is actually quite useful: it means that when we work
with large datasets, we can access and process pieces of these datasets
without the need to copy the underlying data buffer.
The Basic of NumPy Arrays 17

• Creating copies of arrays


The Basic of NumPy Arrays 18

Adding – Removing Elements


np.append(arr, values, axis = none) np.delete(arr, obj, axis = none)
Append values to the end of an array. Return a new array with sub-arrays along
an axis deleted. For a one dimensional
array, this returns those entries not
returned by arr[obj].

np.insert(arr, obj, values, axis = none)


Insert values along the given axis before the
given indices.
Obj: Indicate indices of
sub-arrays to remove along
the specified axis
The Basic of NumPy Arrays 19

Reshaping of Arrays Note:


• The size of the initial array must match
the size of the reshaped array.
• The reshape method will use a no-copy
view of the initial array.

Conversion of a one-dimensional
array into a two-dimensional row
or column matrix .
The Basic of NumPy Arrays 20

Array Concatenation and Splitting


Combine multiple arrays into one, and to conversely split a single array into multiple
arrays
• Concatenation of arrays: np.concatenate.
The Basic of NumPy Arrays 21

• Axis:
The Basic of NumPy Arrays 22

• Splitting of arrays: np.split

Split an array into


multiple sub-arrays
vertically (row-wise)

index
Split an array into multiple
sub-arrays horizontally
(column-wise)

np.vsplit = np.split( ,axis = ?)


np.hsplit = np.split( ,axis = ?)
Computation on NumPy Arrays 23

Arithmetic Operations
+ : np.add
Add arguments element-wise
Computation on NumPy Arrays 24

Broadcasting
Computation on NumPy Arrays 25

Rules of Broadcasting
• Rule 1: If the two arrays differ in their number of dimensions, the shape
of the one with fewer dimensions is padded with ones on its leading (left)
side.
• Rule 2: If the shape of the two arrays does not match in any dimension,
the array with shape equal to 1 in that dimension is stretched to match
the other shape.
• Rule 3: If in any dimension the sizes disagree and neither is equal to 1, an
error israised.
Computation on NumPy Arrays 26

np.exp np.sin
Calculate the exponential of all elements in the input Trigonometric sine, element-wise.
array.

np.cos
np.sqrt Cosine element-wise..
Return the non-negative square-root of an array,
element-wise. np.log
Natural logarithm, element-wise.
Computation on NumPy Arrays 27

np.dot
Dot product of two arrays.
Comparisons, and Boolean Logic 28

Example: Counting Rainy Days


Comparisons, and Boolean Logic 29

Comparisons
Comparisons, and Boolean Logic 30

Boolean Indexing Summing the Values in an Array


Practice 31

Exercises
1. Are there any values greater than 8?
2. Counts the frequency of 3 in x.
3. The sum of the elements is greater than 3 of x.
4. Product of odd numbers of x
5. The Sum of the prime numbers of x
6. How many values less than 6 in each row?
Aggregations: Min, Max, and Everything in Between 32

Minimum and Maximum


Aggregations: Min, Max, and Everything in Between 33
Aggregations: Min, Max, and Everything in Between 34

Example: What Is the Average Height of US Presidents?


Fancy Indexing 35

Exploring Fancy Indexing


Fancy indexing is conceptually simple: it means passing an array of indices to access multiple
array elements at once.
Fancy Indexing 36

Combined Indexing

We can combine fancy indexing with masking:


Fancy Indexing 37

Modifying Values with Fancy Indexing

Where did the 4 go?


Sorting Arrays 38

np.sort and sort method


Sorting along rows or columns
Sorting Arrays 39

Sorts: Partitioning
np.partition takes an array and a number K; the result is a new array with the smallest K values
to the left of the partition, and the remaining values to the right, in arbitrary order.
Sorting Arrays 40

np.argsort np.arpartitiongsort
Returns the indices that would sort an array. Returns the indices that would sort an array.

You might also like