Working with Numpy array in Python Part-2: Basic Functions

In the first part, we have discussed what is Numpy package, how to install and how to use it. In this part we will discuss about basic Numpy array functions of Numpy. If you have not read first part, I will recommend to check it.

First of all, we will import numpy package in the file and then create a Numpy array, on which, we will perform basic array function.

import numpy as np

# create numpy array
x = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
# print array
print(x)

And then from the Terminal go to file location and execute the file with bellow command.

python index.py

It will run the script and print the array.

Basic functions

Let's first work with array functions

ndarray.shape Returns the shape of the array

print(x.shape)
>>> (3, 3)

ndarray.ndim returns number of dimentions of the array

print(x.ndim)
>>> 2

ndarray.itemsize returns byte size of each elements of the array

print(x.itemsize)
>>> 8

ndarray.dtype returns type of array elements

print(x.dtype)
>>> int64

ndarray.size returns total number of elements of the array

print(x.size)
>>> 9

We can access the array by its indexes. Numpy index starts from the 0.

Get first indexed element

print(x[0])
>>> [1 2 3]

Get between two indexed elements including first index

print(x[0:2])
>>> [[1 2 3]
     [4 5 6]]

Get elements from the first indexed

print(x[1:])
>>> [[4 5 6]
     [7 8 9]]

Get elements from the reverse

print(x[-1:])
>>> [[7 8 9]]

Adding or deleting elements from the array.

Add the elements to your array and create new array

x = np.append(x, [1, 2])
print(x)
>>> [1 2 3 4 5 6 7 8 9 1 2]

Remove the elements of the position and create new array

x = np.delete(x, 1)
print(x)
>>> [1 3 4 5 6 7 8 9]

Sort the elements in the array

x = np.sort(x)
print(x)
[[1 3 9]
 [1 4 6]
 [7 8 9]]

Reshape the array columns and rows

x = x.reshape(1, 9)
print(x)
>>> [[1 9 3 4 5 6 7 8 9]]

Now let's see how to create numpy array with other methods

Create array with arrange() and reshape() method

x = np.arange(15).reshape(3, 5)
>>> print(x)
>>> [[ 0  1  2  3  4]
     [ 5  6  7  8  9]
     [10 11 12 13 14]]

Create array with all zero elements

x = np.zeros((2, 2))
>>> print(x)
>>> [[0. 0.]
     [0. 0.]]

Create array with all elements with 1 value

x = np.ones((2,3))
>>> [[1. 1. 1.]
     [1. 1. 1.]]

Create array with constant value

x = np.full((2, 3), 3)
>>> print(x)
>>> [[3 3 3]
     [3 3 3]]

Create sequance array with 4 up to 20

x = np.arange(0, 20, 4)
>>> print(x)
>>> [ 0  4  8 12 16]

create an array with values that are spaced linearly in a specified interval:

x = np.linspace(0, 8, 5)
>>> print(x)
>>> [0. 2. 4. 6. 8.]

In the next part, we will discuss more about basic operations on Numpy array. If you have any suggestion, please let us know in the bellow comment section.

Tags: