[go: up one dir, main page]

0% found this document useful (0 votes)
14 views26 pages

1 Numpy

NumPy is a fundamental package for numerical computing in Python, providing support for arrays, matrices, and mathematical functions. It offers efficient data storage and manipulation, powerful N-dimensional arrays, and broadcasting capabilities. The document covers installation, array creation, attributes, indexing, slicing, and various operations such as reshaping, concatenation, and sorting.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views26 pages

1 Numpy

NumPy is a fundamental package for numerical computing in Python, providing support for arrays, matrices, and mathematical functions. It offers efficient data storage and manipulation, powerful N-dimensional arrays, and broadcasting capabilities. The document covers installation, array creation, attributes, indexing, slicing, and various operations such as reshaping, concatenation, and sorting.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

NUMPY

Introduction to NumPy
Lecturer: Nguyen Tuan Long, Phd
Email: ntlong@neu.edu.vn
Mobile: 0982 746 235
What is NumPy? 2

• Fundamental package for numerical computing in Python.

• Provides support for arrays, matrices, and a large


collection of mathematical functions.
Why NumPy? 3

Benefits:

• Efficient storage and manipulation of numerical data.

• Powerful N-dimensional array object.

• Broadcast capabilities.

• …
Installing NumPy 4

Installation:

• Using pip: pip install numpy

• Using conda: conda install numpy


NumPy Array and List 5

Source: https://www.geeksforgeeks.org/python-lists-vs-numpy-arrays/
NumPy Arrays 6

Creating Arrays:
• From lists: `np.array([1, 2, 3])`
• From scratch: `np.zeros((3, 3))`, `np.ones((2, 2))`, `np.full((2, 2), 7)`,
`np.eye(3)`
• Using functions: `np.arange(0, 10, 2)`, `np.linspace(0, 1, 5)`

• Note: Remember that unlike Python lists, NumPy is


constrained to arrays that all contain the same type
NumPy Array Attributes
import numpy as np
7

np.random.seed(0) # seed for reproducibility


Attributes:
x1 = np.random.randint(10, size=6) # One-dimensional
• `ndarray.ndim`
array
• `ndarray.shape`
x2 = np.random.randint(10, size=(3, 4)) # Two-
• `ndarray.size`
dimensional array
• `ndarray.dtype`
x3 = np.random.randint(10, size=(3, 4, 5)) # Three-
• `ndarray.itemsize` The number of
dimensional array
• `ndarray.nbytes` dimensions
The size of each
dimension
The total size of the
array
The Basic ofimport
NumPy Arrays
numpy as np
8

NumPy Array Attributes


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-
The number of
dimensional array
dimensions
The size of each
dimension
The total size of the
array
Array Indexing and Slicing 9

Array Indexing: Accessing Single Elements


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

0
1
2

0 1 2 3

x[row , column]
The first dimensional The second dimensional
Array Indexing and Slicing 10

Array Slicing: Accessing Subarrays

x[start:stop:s
• tep]• Multidimensional subarrays
One-dimensional subarrays

Subarrays as no-copy views


• 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.
Subarrays with views 11

• 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.
Adding – Removing 12

Adding Removing
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: the index or
indices
Array Reshaping 13

Reshaping arrays
• array.reshape():
• array.flatten():

Note:
• The size of the initial array must match the size of the
reshaped array.
Array Concatenation and Splitting 14

Combining arrays:
• np.concatenate([array1, array2], axis=0)
Array Concatenation and Splitting 15

Combining arrays:
• `np.vstack([array1, array2])` , `np.hstack([array1, array2])`
Array Concatenation and Splitting 16

Splitting arrays:
• `np.split(array, index #or [indecies])` , `np.hsplit()`, `np.vsplit()`
Computation on NumPy Arrays 17

Universal Functions (ufuncs):


• Element-wise operations: `np.add`, `np.subtract`, `np.multiply`,
`np.divide`
• Trigonometric functions: `np.sin`, `np.cos`, `np.tan`
• Aggregation functions: `np.sum`, `np.min`, `np.max`, `np.mean`
import numpy as np
# Tạo một mảng NumPy lớn
arr = np.arange(1e6)
# Sử dụng hàm tổng hợp của NumPy
%timeit np.sum(arr)
# Sử dụng hàm tích hợp sẵn của Python
%timeit sum(arr)
Broadcasting 18

Broadcasting
Broadcasting 19

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 is raised.
Comparisons, Masks, and Boolean Logic 20

Comparisons Boolean masks


Practice 1 21

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?
Fancy Indexing 22

• Indexing with arrays of indices

• Modifying values:

`array[[0, 1], [1, 2]] = 10`


Sorting Arrays 23

np.sort(array, axis = ?) Sorting Along an Axis


Sorting Arrays 24

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 25

np.argsort()
Returns the indices that would sort an array.
Practice 2 26

Exercises for Fancy Indexing, np.sort(), and np.argsort()


Fancy Indexing:
1. Create a 1D array [0-9], select elements at indices [1, 3, 5, 7, 9].
2. Create a 3x3 array [1-9], select diagonal elements [0,0], [1,1], [2,2].
3. Create a 1D array [10-100 step 10], select elements at even indices.
np.sort():
4. Create a 1D array of 10 random ints [0-100], sort it.
5. Create a 3x3 array of random ints [0-100], sort rows and columns.
6. Create a 1D array of random ints [0-100], sort in descending order.
np.argsort():
7. Create a 1D array of 10 random ints [0-100], get sorting indices.
8. Create a 3x3 array of random ints [0-100], get row sorting indices.
9. Create a 1D array of random ints [0-100], sort using indices in descending
order.

You might also like