Sitemap
Chandasingh

Chandasingh

Tech Lover!

NumPy in Python

7 min readOct 2, 2020

--

NumPy stands for “Numeric Python” or “Numerical Python”. It is an open source module of Python which provides fast mathematical functions. NumPy’s main object is the homogeneous multi-dimensional array.

It is a table of elements: usually numbers, all of the same type, indexed by a tuple of positive integers. In NumPy dimensions are called axes and the number of axes is rank

Why use NumPy ?

  • Array-oriented computing
  • Efficiently implemented multi-dimensional arrays
  • Designed for scientific computation
  • Library of high-level mathematical functions

1. Creating Numpy arrays

np.array — Creating NumPy array from Python Lists/Tuple

Numpy arrays can be created from Python lists or tuple in the following way.

Press enter or click to view image in full size

np.zeros — An array with all Zeroes

To create an array with all zeroes the function np.zeros is used

Press enter or click to view image in full size

np.ones — An array with all Ones

To create an array with all ones the function np.ones is used.

Press enter or click to view image in full size

np.full — An array with a given value

To create an array with a given shape and a given value np.full is used.

Press enter or click to view image in full size

np.arange — Creating sequence of Numbers

Press enter or click to view image in full size

np.linspace — Creating an array with evenly distributed numbers

  • Returns an array having a specific number of points
  • Evenly distributed between two values
  • The maximum value is included, contrary to arange
Press enter or click to view image in full size

np.random.rand — Creating an array with random numbers

Let us make a 2x3 matrix having random floats between 0 and 1:

Press enter or click to view image in full size

np.empty — Creating an empty array

To create an uninitialised array with a given shape. Its content is not predictable.

Press enter or click to view image in full size

2. Important attributes of a NumPy object

The NumPy’s array class is called ndarray (N-dimensional array of rectangular data). The important attributes of a ndarray object are -

ndarray.ndim

the number of axes (dimensions) of the array.

Press enter or click to view image in full size

ndarray.shape

the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension.

Press enter or click to view image in full size

ndarray.size

the total number of elements of the array. This is equal to the product of the elements of shape.

Press enter or click to view image in full size

ndarray.dtype

Tells the datatype of the elements in the numpy array. All the elements in a numpy array have the same type.

Press enter or click to view image in full size

ndarray.itemsize

The itemsize attribute returns the size (in bytes) of each item:

Press enter or click to view image in full size

3. Dimensions in NumPy Arrays

0-D Arrays

Press enter or click to view image in full size

1-D Arrays

Press enter or click to view image in full size

2-D Arrays

Press enter or click to view image in full size

3-D Arrays

Press enter or click to view image in full size

Multi-dimensional Arrays

An array can have multiple dimensions. and we can define the number of dimensions in an array by using ndim function.

Press enter or click to view image in full size

4. Reshaping Arrays

The function reshape is used to reshape the NumPy array. The following example illustrates this.

Press enter or click to view image in full size

5. Indexing and Accessing Arrays

Indexing one dimensional NumPy Arrays

Press enter or click to view image in full size

6. Difference with regular Python arrays

  1. If you assign a single value to an ndarray slice, it is copied across the whole slice :
Press enter or click to view image in full size

2. ndarray slices are actually views on the same data buffer. If you modify it, it is going to modify the original ndarray as well.

Press enter or click to view image in full size

3. If you want a copy of the data, you need to use the copy method as another_slice = a[2:6].copy(), if we modify another_slice, a remains same.

Press enter or click to view image in full size

7. Indexing multi dimensional NumPy arrays

Multi-dimensional arrays can be accessed as

Get Chandasingh’s stories in your inbox

Join Medium for free to get updates from this writer.

b[1,2] #1 row, 2 columns

b[1,:] #1 row, all columns

b[:,1] #all rows, 1 column

The following format is used while indexing multi-dimensional arrays:

Array[row_start_index:row_end_index, column_start_index: column_end_index]

Boolean Indexing

We can also index arrays using an ndarray of boolean values on one axis to specify the indices that we want to access.

Press enter or click to view image in full size

8. Linear Algebra with NumPy

Vectors

  • A vector is a quantity defined by a magnitude and a direction.
  • A vector can be represented by an array of numbers called scalars.
Press enter or click to view image in full size

Use of Vectors in Machine Learning

  • Vectors have many purposes in Machine Learning, most notably to represent observations and predictions.
  • For example, say we built a Machine Learning system to classify videos into three categories (good, spam, clickbait) based on what we know about them.
  • For each video, we would have a vector representing what we know about it.

such as :

Video = (10.5, 
5.2,
3.25,
7.0)
  • This vector could represent a video that lasts 10.5 minutes, but only 5.2% viewers watch for more than a minute, it gets 3.25 views per day on an average, and it was flagged 7 times as spam. As you can see, each axis may have a different meaning.
class_probabilities = (0.80,
0.18,
0.02)
  • Based on class_probabilities vector as shown above, our Machine Learning system may predict that there is an 80% probability that it is a spam video, 18% that it is clickbait, and 2% that it is a good video.

9. Basic Operations on NumPy arrays

Addition in NumPy arrays

Addition can be performed on NumPy arrays as shown below. They apply element wise.

Press enter or click to view image in full size

Subtraction in NumPy arrays

Subtraction can be performed on NumPy arrays as shown below. They apply element wise.

Press enter or click to view image in full size

Element wise product in NumPy arrays

Element wise product can be performed on NumPy arrays as shown below:

Press enter or click to view image in full size

Matrix Product in NumPy arrays

Matrix product can be performed on NumPy arrays as shown below.

Press enter or click to view image in full size

Division in NumPy arrays

Division can be performed on NumPy arrays as shown below. They apply element wise.

Press enter or click to view image in full size

Integer Division in NumPy arrays

Division can be performed on NumPy arrays as shown below. They apply element wise.

Press enter or click to view image in full size

Modulus in NumPy arrays

Modulus operator can be applied on NumPy arrays as shown below. They apply element wise.

Press enter or click to view image in full size

Exponents in NumPy arrays

We can find the exponent of each element in a NumPy array in the following way. It is applied element wise.Conditional Operators on NumPy arrays

Conditional operators are also applied element-wise

Conditional Operators on NumPy arrays

Conditional operators are also applied element-wise

Press enter or click to view image in full size

10. Mathematical and statistical functions on NumPy arrays

Statistical functions of NumPy array elements

The ndarray object has methods mean(), min(), max(), sum(), prod(), std() and var() which finds the mean of all the elements in the array regardless of the shape of the numpy array.

Press enter or click to view image in full size
Press enter or click to view image in full size

Other useful ndarray methods

Press enter or click to view image in full size

Summing across different axes

We can sum across different axes of a numpy array by specifying the axis parameter of the sum function.

Press enter or click to view image in full size

Transposing Matrices

The T attribute is equivalent to calling transpose() when the rank is ≥2

Press enter or click to view image in full size

Solving a system of linear scalar equations

The solve function solves a system of linear scalar equations, such as:

2x + 6y = 6

5x + 3y = -9

Press enter or click to view image in full size

I hope it helps!

Happy Learning!!!

--