Next >

# Python - Two Dimensional Array

As in other programming languages, Python also allows us to create a two dimensional(2D) array, where a two-dimensional(2D) array is used to contain multiple arrays, that are holding values of the same type. The elements of a 2D array are arranged in rows and columns.

In python, a simple one-dimensional array is nothing but a list of values i.e. values declared within the square brackets [ ]. Just like that, a two-dimensional(2D) array is multiple lists within a list, where each list is a collection of values and each list is arranged in a separate row.

## Creating a two-dimensional array in Python

To create a 2D array, we need to import the numpy module and call its zeros() method, just like we did when we created a 1D array, though this time, there is a slight difference in the number of parameters we call the zeros() function with.

Note : Calling the zeros method, 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 the shape of an array and could be given either of the values -
- An integer value i.e. the total number of elements in a 1D array.
- A list of integer values i.e. the 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 a 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 a 2D array

• In order to create a 2D array by calling zeros() function, we need to pass a list of two values where the first value represents the number of rows and the second value represents the number of columns in a 2D array.

A 2D array holds multiple arrays, where all the arrays have values of the same type. Let us create some different types of a 2D array, for example -
• A 2D array of int values
• A 2D array of float values
• A 2D array of str i.e. string values
• A 2D array of double values.

``````from numpy import zeros

# Calling zeros() to create an int array of 2 rows and 2 columns
a = zeros([2,2], int)

print('A 2D array of int values  : ')
print(a)

# Calling zeros() to create a float array of 2 rows and 3 columns
a = zeros([2,3], float)

print('A 2D array of float values  : ')
print(a)

# Calling zeros() to create a float array of 2 rows and 2 columns i.e datatype is float by default.
a = zeros([2,2])

print('A 2D array of default float values  : ')
print(a)

# Calling zeros() to create a double array of 2rows and 2 columns
a = zeros([2,2], double)

print('A 2D array of of double values  : ')
print(a)

# Calling zeros() to create a string array of 2 rows and 4 columns
a = zeros([2,4], str)

print('A 2D array of string values  : ')
print(a)

# Calling zeros() to create a bool array of 2 rows and 2 column bool
a = zeros([2,1], bool)

print('A 2D array of bool values  : ')
print(a)
``````

## Output

``````A 2D array of int values  :
[[0 0]
[0 0]]
A 2D array of float values  :
[[0. 0. 0.]
[0. 0. 0.]]
A 2D array of default float values  :
[[0. 0.]
[0. 0.]]
A 2D array of of double values  :
[[0. 0.]
[0. 0.]]
A 2D array of string values  :
[['' '' '' '']
['' '' '' '']]
A 2D array of 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. a boolean array has been initialized to the boolean value False(a boolean equal of zero).

• ## Calling ones() method to create a 2D array

• Similar to zeros() method, we could also use the ones() method of numpy module to create different types of a 2D 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 int array of 2 rows and 2 columns
a = ones([2,2], int)

print('A 2D array of int values  : ')
print(a)

# Calling ones() to create a float array of 2 rows and 3 columns
a = ones([2,3], float)

print('A 2D array of float values  : ')
print(a)

# Calling ones() to create a float array of 2 rows and 2 columns i.e datatype is float by default.
a = ones([2,2])

print('A 2D array of default float values  : ')
print(a)

# Calling ones() to create a double array of 2rows and 2 columns
a = ones([2,2], double)

print('A 2D array of of double values  : ')
print(a)

# Calling ones() to create a string array of 2 rows and 4 columns
a = ones([2,4], str)

print('A 2D array of string values  : ')
print(a)

# Calling ones() to create a bool array of 2 rows and 2 column bool
a = ones([2,1], bool)

print('A 2D array of bool values  : ')
print(a)``````

## Output

``````A 2D array of int values  :
[[1 1]
[1 1]]
A 2D array of float values  :
[[1. 1. 1.]
[1. 1. 1.]]
A 2D array of default float values  :
[[1. 1.]
[1. 1.]]
A 2D array of of double values  :
[[1. 1.]
[1. 1.]]
A 2D array of string values  :
[['' '' '' '']
['' '' '' '']]
A 2D array of 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. boolean array has been initialized to the boolean value True(a boolean equal of one).

• ## Calling array() function to create and initialize a 2D 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.

In python, a simple one-dimensional array is nothing but a list of values. Just like that, a two-dimensional(2D) array is multiple lists within a list, where each list is a collection of values and each list is arranged in a separate row.

Syntax of array() function -
``zeros(list, datatype)``

Parameters Description
list A list is a list containing multiple lists, where each list corresponds to an array of values. A list of values is always contained in square brackets i.e. [ ]

This is a non-optional attribute.
datatype datatype is the datatype of the elements in the array, could be given either of the values like int, float, str, double. 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 data type.

This is an optional attribute and its default value is a float.

``````from numpy import array

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

print('A 2D array of int values  : ')
print(a)

# Calling array() to create an float array of 2 rows and 2 columns
a = array([[4.3,5.2], [1.1,2.3]], float)

print('A 2D array of float values  : ')
print(a)

# Calling array() to create an array(2 rows and 3 columns) of type based on the type of values
a = array([[4.3,5.2,1.2], [1.1,2.3,3.4]])

print('A 2D array of float values  : ')
print(a)

# Calling array() to create a double array of 3 rows and 2 columns
a = array([[2.2, 3.4], [4.5,6.7], [3.4,7.8]], double)

print('A 2D array of of double values  : ')
print(a)

# Calling array() to create a string array of 2 rows and 3 columns
a = array([['hi','ABC', '8'], ['A', 'hello', 'Z']], str)

print('A 2D array of string values  : ')
print(a)

# Calling array() to create a bool array of 3 rows and 2 columns
a = array([[True,False], [False,True], [True,True]], bool)

print('A 2D array of bool values  : ')
print(a)``````

## Output

``````A 2D array of int values  :
[[5 4 3]
[4 2 1]]
A 2D array of float values  :
[[4.3 5.2]
[1.1 2.3]]
A 2D array of float values  :
[[4.3 5.2 1.2]
[1.1 2.3 3.4]]
A 2D array of of double values  :
[[2.2 3.4]
[4.5 6.7]
[3.4 7.8]]
A 2D array of string values  :
[['hi' 'ABC' '8']
['A' 'hello' 'Z']]
A 2D array of bool values  :
[[ True False]
[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

The numpy module provides us many of its important functions using which we could perform 2D array 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 a 2D 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 *

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

print('A 2D array of int values  : ')
print(a)

# Extracting the first element of an array using its index 
print('Value at 0th row and 0th column : ', a)

# Extracting the second element of an array using its index 
print('Value at 0th row and 1st column : ', a)

# Extracting the third element of an array using its index 
print('Value at 0th row and 2nd column : ', a)

# Extracting the four element of an array using its index 
print('Value at 1st row and 0th column : ', a)

# Extracting the four element of an array using its index 
print('Value at 1st row and 1st column : ', a)

# Extracting the four element of an array using its index 
print('Value at 1st row and 2nd column : ', a)``````

## Output

``````A 2D array of int values  :
[[5 4 3]
[4 2 1]]
Value at 0th row and 0th column :  5
Value at 0th row and 1st column :  4
Value at 0th row and 2nd column :  3
Value at 1st row and 0th column :  4
Value at 1st row and 1st column :  2
Value at 1st row and 2nd column :  1``````

• ## Traversing through a 2D array using for loop

• As we know that in Python, a list makes an array and a 2D array is a list holding multiple lists, where each list is a collection of values. We could traverse through elements of a 2D array using the nested for loop i.e. one for loop is nested into another for loop.

• The outer for loop is used to access each list i.e. each array of values, within a list.
• The inner for loop is used to access values of individual list i.e. array.

``````from numpy import array

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

print('A 2D array of int values  : ')
print(a)

print('Accessing each array element using for loop :')

# Traversing through the 2D array and printing its each element using a nested for loop
# Outer for loop is used to access each list i.e. each array of values, within a list
# the inner for loop is used to access values of individual list i.e. array.
for x in a:
for y in x:
print(y)``````

## Output

``````A 2D array of int values  :
[[5 4 3]
[4 2 1]]
Accessing each array element using for loop :
5
4
3
4
2
1``````

• ## Traversing through a 2D 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.

``````import array as arr

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

# The index of first element of an array i.e. 
x = 0
y = 0

print('Accessing each array element using while loop :')

# The first len() function gives us the total number of lists in a list
# The second len() function gives us total number of values in the first list i.e. a and all the lists have same number of values
# Outer for loop is used to access each list i.e. each array of values, within a list
# the inner whule loop is used to access values of an individual list i.e. array.
while(x<len(a)):
while(y<len(a)):
print(a[x][y])
y = y + 1
x = x + 1
y = 0``````

## Output

``````A 2D array of int values  :
[[5 4 3]
[4 2 1]]
Accessing each array element using while loop :
5
4
3
4
2
1``````

• ## Inserting an element into a 2D 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 This 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 int array of 2 rows and 3 columns
a = array([[5,4,3], [4,2,1]], int)

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

# Calling the insert() function to insert integer value 7 at index 2 in axis  = 1 i.e. in the 2nd row
a = insert(a, 2, 7, axis=0)

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

# Calling the insert() function to insert integer value 9 at index 1 in axis  = 1 i.e. in the 1st column
a = insert(a, 1, 9, axis=1)

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

## Output

``````Array of int values  :
[[5 4 3]
[4 2 1]]
Modified array of int values  :
[[5 4 3]
[4 2 1]
[7 7 7]]
Modified array of int values  :
[[5 9 4 3]
[4 9 2 1]
[7 9 7 7]]``````

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 a 2D array

• We can delete an element from an array using the delete() function of 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). Let us see an example.

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 the axis is 1, the value is deleted from the column. - if the axis is 0, the value is deleted from the row.

This is an optional attribute. If the value of axis is not provided then the 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 int array of 2 rows and 3 columns
a = array([[5,4,3], [4,2,1]], int)

# Calling the delete() function to delete from index 1 and axis = 0 i.e. 0th row
a = delete(a, 0, 0)

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

# Calling the delete() function to delete from index 1 and axis = 1 i.e. 1st column
a = delete(a, 1, axis=1)

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

## Output

``````Array of int values  :
[[5 4 3]
[4 2 1]]
Modified array of int values  :
[[4 2 1]]
Modified array of int values  :
[[4 1]]``````

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 a 2D 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 the array on which we want to perform the append operation.

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

This is a non-optional attribute.
axis This is the axis along we are going to append the values-
- if the 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 axis is assigned None and the append operation is is applied to the flattened array and we get a flattened array in return.

``````from numpy import *

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

# Calling the append() function to append a list of elements to its end # Calling the delete() function to delete from index 0 and axis = 0 i.e. 0th row
a = append(a, [[66,33,44]], 0)

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

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

## Output

``````Array of int values  :
[[5 4 3]
[4 2 1]]
Modified array of int values  :
[[ 5  4  3]
[ 4  2  1]
[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.   