< Prev
Next >

Python - Array from Numpy Module

In our previous article, we have introduced you to the concept of an array in Python and how we could create an array and perform array operations using the array module of Python. In this article, we are going to introduce you another module named numpy which stands for numerical python, using which we could create an array and also perform general and numerical array operations.

Creating an array in Python using the numpy module

In order to create an array in Python using a special module named numpy, we need to import the numpy module and call its zeros method, which will create an array with all its elements initialized to zero. Let us look at the syntax of this function.

Syntax of zeros() function -
``zeros(shape, datatype, order)``

Parameters Description
shape shape is shape of the array and could be given either of the values -
- An integer value i.e. total number of elements in a 1D array.
- A list of integer values i.e. dimensions of a multi-dimensional array.

This is a non-optional attribute.
datatype datatype is the data type of the elements in the array, could be given either of the values like int, float, str, double..

This is an optional attribute and its default value is float.
order order is the order which is used to specify whether to store multi-dimensional array in row-major (C-style) or column-major (Fortran-style) order in memory.

This is an optional attribute and usually we don't specify it.

• Calling zeros() function to create an array

• An array could only contain elements of the same type. Using the zeros() method of the numpy module, let us create some different types of array, for example -
• An array of int values
• An array of float values
• An array of str i.e. string values
• An array of double values.

``````from numpy import zeros

# Calling zeros() to create an array of 2 int values
a = zeros([2], int)
print('Array of two int values  : ', a)

# Calling zeros() to create an array of 2 float values
a = zeros([2], float)
print('Array of two float values : ', a)

# Calling zeros() to create an array of 4 float values i.e datatype is float by default.
a = zeros(4)
print('Array of four float values : ', a)

# Calling zeros() to create an array of 2 double values
a = zeros([2], double)
print('Array of two double values : ', a)

# Calling zeros() to create an array of 3 str values i.e. string values
a = zeros([3], str)
print('Array of three str values : ', a)

# Calling zeros() to create an array of 2 bool i.e. boolean values
a = zeros([2], bool)
print('Array of two bool values : ', a)
``````

Output

``````Array of two int values  :  [0 0]
Array of two float values :  [0. 0.]
Array of four float values :  [0. 0. 0. 0.]
Array of two double values :  [0. 0.]
Array of three str values :  ['' '' '']
Array of two bool values :  [False False]]``````

As you can see, all the elements of each array will be initialized to zero and the elements of the last bool i.e. boolean array has been initialized to the boolean value False(a boolean equal of zero).

• Calling ones() method to create an array

• Similar to zeros() method, we could also use the ones() method of the numpy module to create different types of an array, though there is a slight difference i.e. elements of an array created by calling the ones() method are initialized to one and not zero.

``````from numpy import ones

# Calling ones() to create an array of 2 int values
a = ones([2], int)
print('Array of two int values  : ', a)

# Calling ones() to create an array of 2 float values
a = ones([2], float)
print('Array of two float values : ', a)

# Calling ones() to create an array of 4 float values i.e datatype is float by default.
a = ones(4)
print('Array of four float values : ', a)

# Calling ones() to create an array of 2 double values
a = ones([2], double)
print('Array of two double values : ', a)

# Calling ones() to create an array of 3 str values i.e. string values
a = ones([3], str)
print('Array of three str values : ', a)

# Calling ones() to create an array of 2 bool i.e. boolean values
a = ones([2], bool)
print('Array of two bool values : ', a)
``````

Output

``````Array of two int values  :  [1 1]
Array of two float values :  [1. 1.]
Array of four float values :  [1. 1. 1. 1.]
Array of two double values :  [1. 1.]
Array of three str values :  ['1' '1' '1']
Array of two bool values :  [ True  True]``````

As you can see, all the elements of each array will be initialized to one and the elements of the last bool i.e. a boolean array has been initialized to the boolean value True(a boolean equal of one).

• Calling array() function to create and initialize an array

• Apart from the zeros() and ones() functions which initialize the elements of an array to zero or one, we could call the array() function of the numpy module, using which we not just create different types of an array but can also initialize the elements of an array, as per our choice.

To call the array() function, we must pass two parameters in the following sequence -
• A list of values that we want to become the elements of an array which we are creating. A list of values is always contained in square brackets i.e. [ ]
• A datatype of an array that we want to create. If the values passed in a list are not exactly of the datatype mentioned in the array function, they will be converted to the mentioned datatype.

``````from numpy import array

# Calling array() to create an array of int values
a = array([5, 2, 7, 8], int)
print('Array of int values  : ', a)

# Calling array() to create an array of float values
a = array([2.4, 7, 8.5], float)
print('Array of float values : ', a)

# Calling array() to create an array of type based on the type of values
a = array([5, 2, 7, 8])
print('Array of int values : ', a)

# Calling array() to create an array of double values
a = array([5.94, 2.34, 7, 8], double)
print('Array of double values : ', a)

# Calling array() to create an array of str i.e. string values
a = array(['Hi', 'XYZ', 8], str)
print('Array of str values : ', a)

# Calling array() to create an array of bool i.e. boolean values
a = array([False, True, True, 8], bool)
print('Array of bool values : ', a)``````

Output

``````Array of int values  :  [5 2 7 8]
Array of float values :  [2.4 7.  8.5]
Array of values :  [5 2 7 8]
Array of double values :  [5.94 2.34 7.   8.  ]
Array of str values :  ['Hi' 'XYZ' '8']
Array of bool values :  [False  True  True  True]``````

As you can see, we have created and have initialized the elements of each array by calling the array() function and passing it the initialized elements and the datatype i.e. int, float, double, str, bool of the array we want to create.

Note : When we don't pass the datatype to the array() function, the type of an array created depends on the type of its elements passed to the function.

Array Operations

Using the array module, we could perform array related operations, such as -
• Traversing through an array
• Extracting an element from an array
• Inserting an element to a specific index in an array
• Appending an element to the end of an array
• Deleting an element from an array

• Extracting an element from an array

• We could extract any element from an array from its index position i.e. the first element of an array is stored at index zero and so on.

``````from numpy import array

# Calling array() to create an array of int values
a = array([5, 2, 7, 8], int)

print('Array of two int values  : ', a)

# Extracting the first element of an array using its index i.e 0
print(a[0])

# Extracting the second element of an array using its index i.e 1
print(a[1])

# Extracting the third element of an array using its index i.e 2
print(a[2])

# Extracting the four element of an array using its index i.e 3
print(a[3])``````

Output

``````5
2
7
8``````

• Traversing through an array using for loop

• We could traverse through elements of an array using a for loop and print all of its elements. Let us see how it is done.

``````from numpy import array

# Calling array() to create an array of int values
a = array([1, 5, 4, 3, 2], int)

# Traversing through the array and printing its each element using a for loop
for x in a:
print(x)``````

Output

``````1
5
3
4
2``````

• Traversing through an array using while loop

• We could traverse through an array and extract each of its element using its index position, from within a while loop. For this, we will also have to use the len() function of object class, which takes any iterable type i.e. list, tuple, array, etc in its parameters and returns the total number of elements in it.

``````from numpy import array

# Calling array() to create an array of int values
a = array([1, 5, 4, 3, 2], int)

# The index of first element of an array
i = 0

# Using while loop to extract each of its element using while loop
# And len() function which takes an iterable type in its parameters i.e. list, tuple, array etc
while(i<len(a)):
print(a[i])
i = i + 1``````

Output

``````1
5
3
4
2``````

• Inserting an element into an array

• Unlike programming languages like C, C++, where the once an array is created, some new elements could not be inserted to it but using the numpy module of Python, we could insert new elements to an array.

Syntax of insert() function -
``insert(arr, obj, values, axis)``

Parameters Description
arr The name of array on which we want to perform the insert operation.

This is a non-optional attribute.
obj This is an object that defines the index position(where we want to insert the new element). .

This is an non-optional attribute.
values The values that we want to insert in an array.

This is an non-optional attribute.
axis This is the axis along we are going to insert the values-
- if axis is 1, the value is inserted in the column.
- if axis is 0, the value is inserted in the row.

This is an optional attribute. If the value of axis is not provided then we get a flattened array.

``````from numpy import *

# Calling array() to create an array of 2 int values
a = array([5, 2, 7, 8], int)

print('Array of int values  : ', a)

# Calling the insert() function to insert integer value 99 at index 2 i.e. starting index in array is 0
a = insert(a, 2, 99)

print('Modified array of int values  : ', a)``````

Output

``````Array of int values  :  [5 2 7 8]
Modified array of int values  :  [5  2 99  7  8]``````

Note: The insert() function does not work on the original array but only on the copy of an array, hence in order to reflect the changes made by the insert() function, we must assign the result of insert() function i.e. back to the reference variable to the original array.

• Deleting an element from its index in an array

• We can delete an element from an array using the delete() function of the numpy module, passing the array name on which we want to perform the delete operation and the index position(from where we want to delete the element from the array).

Syntax of delete() function -
``delete(arr, obj, axis)``

Parameters Description
arr The name of array on which we want to perform the delete operation.

This is a non-optional attribute.
obj This is an object that defines the index position(where we want to delete the element). .

This is an non-optional attribute.
axis This is the axis along we are going to insert the values -
- if axis is 1, the value is deleted from the column. - if axis is 0, the value is deleted from the row.

This is an optional attribute. If the value of axis is not provided then axis is assigned None and the obj index is applied to the flattened array and we get a flattened array in return.

``````from numpy import *

# Calling array() to create an array of 2 int values
a = array([5, 2, 7, 8], int)

print('Array of int values  : ', a)

# Calling the delete() function to delete the value at index 2 i.e. starting index in array is 0
a = delete(a, 2)

print('Modified array of int values  : ', a)``````

Output

``````Array of int values  :  [5  2  7  8]
Modified array of int values  :  [5 2 8]``````

Note : The delete() function does not work on the original array but only on the copy of an array, hence in order to reflect the changes made by the delete() function, we must assign the result of delete() function i.e. back to the reference variable to the original array.

• Appending new elements to an array

• We can append new elements to the end of an array using the append() function of numpy module, by passing it an element or a list of elements which will be appended to the end of an array. Let us see an example.

Syntax of append() function -
``append(arr, values, axis)``

Parameters Description
arr The name of array on which we want to perform the append operation.

This is a non-optional attribute.
values The values that we want to append to an array.

This is an non-optional attribute.
axis This is the axis along we are going to append the values-
- if axis is 0, the value is appended to the last row i.e. at the end of a 2D array.

This is an optional attribute. If the value of axis is not provided then we get a flattened array.

``````from numpy import *

# Calling array() to create an array of int values
a = array([5, 2, 7, 8], int)

print('Array of int values  : ', a)

# Calling the append() function to append a list of elements to its end
a = append(a, [66,33,44])

print('Modified array of int values  : ', a)``````

Output

``````Array of int values  :  [5 2 7 8]
Modified array of int values  :  [5  2  7  8 66 33 44]``````

Note: The append() function does not work on the original array but only on the copy of an array, hence in order to reflect the changes made by the append() function, we must assign the result of append() function i.e. back to the reference variable to the original array.