Numpy
Numpy
• 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
…
Creating Numpy Arrays 4
np.random.random(size=None)
Return random floats in the half-open
interval [0.0, 1.0).
Creating Numpy Arrays 8
0
1
2
0 1 2 3
x[row , column]
The first dimensional The second dimensional
The Basic of NumPy Arrays 13
x[start:stop:step]
• One-dimensional subarrays
The Basic of NumPy Arrays 15
• Multidimensional subarrays
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
Conversion of a one-dimensional
array into a two-dimensional row
or column matrix .
The Basic of NumPy Arrays 20
• Axis:
The Basic of NumPy Arrays 22
index
Split an array into multiple
sub-arrays horizontally
(column-wise)
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
Comparisons
Comparisons, and Boolean Logic 30
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
Combined Indexing
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.