1 Numpy
1 Numpy
Introduction to NumPy
Lecturer: Nguyen Tuan Long, Phd
Email: ntlong@neu.edu.vn
Mobile: 0982 746 235
What is NumPy? 2
Benefits:
• Broadcast capabilities.
• …
Installing NumPy 4
Installation:
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)`
0
1
2
0 1 2 3
x[row , column]
The first dimensional The second dimensional
Array Indexing and Slicing 10
x[start:stop:s
• tep]• Multidimensional subarrays
One-dimensional subarrays
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].
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
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
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
• Modifying values:
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