# NumPy

NumPy is a Linear Algebra Library for Python. We can use it to create vectors and arrays or matrices of numbers and perform mathematical operations on them. It is one of the most important libraries in Data Science as it is relied upon by almost all of the libraries in the Python Data Science stack as one of their main building blocks.

You are encouraged to scroll through the official documentation of NumPy for clearer understanding.

This tutorial is intended for those readers who have basic understanding of the Python syntax.

## Installing NumPy

You can install numpy simply using pip:

pip install numpy

## Using NumPy

Once you’ve installed NumPy you can import it as a library:

```
import numpy as np
```

## Arrays

In NumPy, Arrays can be one-dimensional, called vectors; or two-dimensional, called matrices. However, even a matrix can consist of just one row or column.

### Creating Arrays

We can create NumPy Arrays using the built-in methods, as well as convert Python lists into NumPy arrays.

### Using Built-in Methods

There are lots of built-in methods to generate NumPy Arrays:

**arange**

Returns evenly spaced integers within the given interval.

```
np.arange(0,10)
```

You can also mention the step-size as the third parameter.

```
np.arange(0,11,2)
```

### zeros and ones

Generates arrays of zeros or ones of the given shape.

```
np.zeros(5) #an integer as parameter indicates a vector of given length
```

```
np.zeros((3,5)) #a tuple of two integers as parameter indicates a matrix with (number of rows, number of columns)
```

Similarly, for the function ‘ones’:

```
np.ones(5)
```

```
np.ones((5,5))
```

### linspace

Returns evenly spaced real numbers over the given interval.

```
np.linspace(0,10,3) #The parameters are start point, end point, and the number of elements to be returned (50 by default)
```

```
np.linspace(0,10,50)
```

We can also mention the data type of elements to be returned:

```
np.linspace(0,10,4,dtype=int)
```

### eye

Returns an identity matrix of the given size.

Here only one parameter is required as the output is always a square matrix.

```
np.eye(4)
```

### Creating Random Arrays

These are specially useful for creating dummy data or initialising random data. NumPy has many methods to create arrays with random values:

### rand

Creates an array of the specified shape and with random samples from a Uniform Distribution over [0, 1).

```
np.random.rand(2)
```

```
np.random.rand(2,3)
```

### randn

Creates an array of the specified shape and with random samples from the Standard Normal Distribution of mean 0 and variance 1.

```
np.random.randn(2)
```

```
np.random.randn(2,3)
```

### randint

Returns one or more random integers from the given range.

```
np.random.randint(1,10) #the parameters are low (inclusive) and high (exclusive) of the range
```

```
np.random.randint(1,100,10) #we can use the third parameter to specify the number of elements in the returned array
```

## Converting a Python List to NumPy Array

We can create a NumPy array by converting a python list or even list of lists.

Let’s start by creating a list.

```
some_list = [2,5,1,4,7]
some_list
```

We can convert it into a NumPy array by simply calling out the ‘array’ function:

```
np.array(some_list)
```

If the list contains even one floating point value, all the elements of the resulting array will be converted into float.

```
another_list = [2,5,1,4,7.0]
np.array(another_list)
```

To create a matrix, we can use a list of lists. Each individual inner list will represent one row of the resulting matrix.

```
some_matrix = [[1,2,3],[4,5,6],[7,8,9]]
some_matrix
```

```
np.array(some_matrix)
```

## Array Attributes and Methods

There are many useful attributes and methods for a Numpy array.

Let’s start by building two arrays as follows:

```
my_array = np.arange(30)
random_array = np.random.randint(0,50,10)
```

```
my_array
```

```
random_array
```

### Reshape

Returns an array with the same data but of the specified new shape.

```
my_array.reshape(6,5)
```

It works only if the specified shape can accomodate all the elements of the original array.

If N is the number of elements, and (R,C) is the new shape, then the following condition should hold:

N = R * C

However, reshape allows you to skip one of the parameters (either the number of rows or the number of columns, but not both!).

To do this, you can just specify -1 as one of the arguments, and NumPy will determine the suitable value on its own.

```
my_array.reshape(3,-1)
```

```
my_array.reshape(-1,6)
```

### max, min, argmax, argmin

These are used to return the maximum or minimum values, or their index locations.

```
random_array #the one we declared above
```

```
random_array.max() #returns the largest element
```

```
random_array.argmax() #returns the index value of the largest element
```

```
random_array.min() #returns the smallest element
```

```
random_array.argmin() #returns the index value of the smallest element
```

## Shape

It returns the shape of the array. Please note that shape is just an attribute of the NumPy arrays; it is not a method.

```
my_array.shape #this is a vector, hence only one term is returned.
```

To convert it into a one-dimensional matrix, we will use the ‘reshape’ function:

```
my_array.reshape(1,30)
```

```
my_array.reshape(1,30).shape #this is a matrix
```

### dtype

It is used to return the datatype of the array. This is also an attribute, not a method.

```
my_array.dtype
```

## Indexing and Selection

This allows us to select specific elements or groups of elements from an array.

```
my_array #declared above
```

### Indexing and Slicing

It is used to get the element at a particular index or in a particular range. It is similar to the method in Python Lists.

```
my_array[10]
```

```
my_array[1:5] #low inclusive and high exclusive
```

We can skip the low value to indicate “start from the first element”, and the high value to indicate “go all the way till the end”:

```
my_array[:5]
```

```
my_array[24:]
```

```
my_array[:]
```

### Indexing and Slicing a Matrix

```
some_matrix #declared above
```

```
np_matrix = np.array(some_matrix)
np_matrix
```

```
np_matrix[1] #gives specified row
```

```
np_matrix[1][2] #gives specified element: matrix[row][column]
```

```
np_matrix[1,2] #same as previous: matrix[row,column]
```

```
np_matrix[1:3] #slicing rows in matrix
```

```
np_matrix[1:3,1:3] #slicing rows as well as columns in matrix
```

```
np_matrix[:2,1:]
```

```
random_array #declared above
```

```
boolean_array = random_array > 20 #returns an aray with value=True where condition holds and value=False otherwise
boolean_array
```

```
random_array[boolean_array] #returns only those elements for which the corresponding element in boolean_array is True
```

```
random_array[random_array > 20] #same as previous
```

## NumPy Operations

There are many mathematical and universal operations which can be applied on NumPy arrays.

Let’s start by creating a new array:

```
new_array = np.arange(10)
new_array
```

```
new_array + new_array #returns 'element by element' sum
```

```
new_array - new_array #returns 'element by element' difference
```

```
new_array * new_array #returns 'element by element' product
```

```
new_array / new_array #returns 'element by element' quotient
```

The first element is 0/0, which is not allowed in mathematics. However, instead of giving an error, Python represents it as a nan (not a number)

```
new_array ** 2 #returns each element to the power 2
```

```
1 / new_array #returns inverse of each element
```

Here, the first element is 1/0, which represents infinity. Python indicates this value by ‘inf’.

```
np.sqrt(new_array) # same as new_array ** (1/2)
```

```
np.sin(new_array) #returns the sine value of each element
```

There are loads of other functions in NumPy, which are very handy and intended to make your lives a lot easier.

I strongly recommend going through the official documentation right here.

This article is just for the starters. 😉

If you have any doubt, feel free to comment below. Happy learning 🙂

### Pranav Gupta

I am an avid learner and never shy off from working hard or working till late. I am also a passionate reader, and love to read thriller novels, Jeffrey Archer being the favorite writer.

LinkedIn: https://www.linkedin.com/in/prnvg/

#### Latest posts by Pranav Gupta (see all)

- Data Science… Where to START ?! - June 28, 2018
- The Subtle Differences among Data Science, Machine Learning, and Artificial Intelligence - June 5, 2018
- Introductory Guide to NumPy - December 12, 2017