Home Numpy
Post
Cancel

Numpy

Open In Colab

What is Numpy?

Numpy is the python package that allows us to work with multidimensional array objects. It is extremely useful for scientific computing using Python, and is widely used in various fields such as Machine Learning for Data Analysis etc.

Array

An Array in Numpy is a matrix of elements having the same datatype. An array class in Numpy is known as ndarray (N-dimensional array).

Creating a Numpy Array

1
2
3
4
5
6
7
8
9
10
# Using array() method

import numpy as np

arr = np.array([[1, 4, 7],
                [7, 2, 9],
                [5, 0, 1]])

print('Created Array:\n {}'.format(arr))

1
2
3
4
Created Array:
 [[1 4 7]
 [7 2 9]
 [5 0 1]]
1
2
3
4
5
6
7
8
# Using empty() method
# numpy.empty(shape, dtype = float, order = ‘C’) : Return a new array of given shape and type, with random values.

import numpy as np

arr = np.empty((3, 3), dtype=int)
print('Empty Array:\n {}'.format(arr))

1
2
3
4
Empty Array:
 [[1 4 7]
 [7 2 9]
 [5 0 1]]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Using eye() method
# numpy.eye(R, C = None, k = 0, dtype = type <‘float’>) : The eye tool returns a 2-D array with  1’s as the diagonal and  0’s elsewhere.
# The diagonal can be main, upper, lower depending on the optional parameter k.
# A positive k is for the upper diagonal, a negative k is for the lower, and 0 k (default) is for the main diagonal.

import numpy as np

arr1 = np.eye(4, 4, k=0, dtype=int)
print('Matrix: \n {}'.format(arr1))

arr2 = np.eye(4, 4, k=1, dtype=int)
print('Matrix: \n {}'.format(arr2))

arr3 = np.eye(4, 4, k=-1, dtype=int)
print('Matrix: \n {}'.format(arr3))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Matrix: 
 [[1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]]
Matrix: 
 [[0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]
 [0 0 0 0]]
Matrix: 
 [[0 0 0 0]
 [1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]]
1
2
3
4
5
6
7
8
# Using identity() method
# numpy.identity(n, dtype = None) : Return a identity matrix i.e. a square matrix with 1's on the main diagonal.

import numpy as np

arr = np.identity(4)
print('Identity Matrix: \n {}'.format(arr))

1
2
3
4
5
Identity Matrix: 
 [[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Using ones() method
# numpy.ones(shape, dtype = None, order = 'C')  Returns a new array of given shape and type, with ones.

import numpy as np

arr_one = np.ones([3, 3])
print('Matrix with 1 as elements: \n {}'.format(arr_one))

# Using zeros() method
# numpy.zeros(shape, dtype = None, order = 'C')  Returns a new array of
# given shape and type, with zeros.

arr_zero = np.zeros([3, 3])
print('Matrix with 0 as elements: \n {}'.format(arr_zero))

1
2
3
4
5
6
7
8
Matrix with 1 as elements: 
 [[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
Matrix with 0 as elements: 
 [[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Using asarray() method
# numpy.asarray()function is used to convert input to an array. 
# Input can be lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.

import numpy as np

arr_tuple1 = ([1,6,5],[2,7,6])
print('Input: {}'.format(arr_tuple1))

arr1 = np.asarray(arr_tuple1)
print('Array: \n {}'.format(arr1))


# Uncomment these lines to see what happens if you try to convert inputs having different lengths into an array
# arr_tuple2 = ([1,6,5],[2,7])
# print('Input: {}'.format(arr_tuple2))

# arr2 = np.asarray(arr_tuple2)
# print('Array: \n {}'.format(arr2))
1
2
3
4
Input: ([1, 6, 5], [2, 7, 6])
Array: 
 [[1 6 5]
 [2 7 6]]
1
2
3
4
5
6
7
8
9
10
11
# Using arange() method
# arange([start,] stop[, step,][, dtype]) : Returns an array with evenly spaced elements as per the interval.

import numpy as np

arr_1 = np.arange(0, 20)
print('Array 1: {}'.format(arr_1))

arr_2 = np.arange(2, 20, 3)
print('Array 2: {}'.format(arr_2))

1
2
Array 1: [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
Array 2: [ 2  5  8 11 14 17]
1
2
3
4
5
6
7
8
9
10
11
# Using linspace() method
# Returns number spaces evenly w.r.t interval. Similar to numpy.arange() function but instead of step it uses sample number.

import numpy as np

arr_1 = np.linspace(start=0, stop=10, num=5, retstep=True, dtype=int)
print('Arr 1:\n {}'.format(arr_1))

arr_2 = np.linspace(start=0, stop=10, num=5, retstep=False, dtype=int)
print('Arr 2:\n {}'.format(arr_2))

1
2
3
4
Arr 1:
 (array([ 0,  2,  5,  7, 10]), 2.5)
Arr 2:
 [ 0  2  5  7 10]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Using diag() method
# Extracts and construct a diagonal array
# k=0 denotes main diagonal. k>0 denotes diagonal above main diagonal. k<0 denotes diagonal below main diagonal

import numpy as np

arr = np.array([[1, 2, 6],
                [4, 8, 1],
                [6, 9, 0]])

print('Array:\n {}'.format(arr))

diag_1 = np.diag(arr, k=0)
print('Main diag: {}'.format(diag_1))

diag_2 = np.diag(arr, k=1)
print('Upper diag: {}'.format(diag_2))

diag_3 = np.diag(arr, k=-1)
print('Lower diag: {}'.format(diag_3))

1
2
3
4
5
6
7
Array:
 [[1 2 6]
 [4 8 1]
 [6 9 0]]
Main diag: [1 8 0]
Upper diag: [2 1]
Lower diag: [4 9]
1
2
3
4
5
6
7
8
9
10
11
# Using diagflat() method
# Create a two-dimensional array with the array_like input as a diagonal to the new output array.

import numpy as np

print("diagflat use on main diagonal : \n", np.diagflat([1, 7, 6], k=0))

print("\ndiagflat above main diagonal : \n", np.diagflat([1, 7, 6], k=1))

print("\ndiagflat below main diagonal : \n", np.diagflat([1, 7, 6], k=-1))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
diagflat use on main diagonal : 
 [[1 0 0]
 [0 7 0]
 [0 0 6]]

diagflat above main diagonal : 
 [[0 1 0 0]
 [0 0 7 0]
 [0 0 0 6]
 [0 0 0 0]]

diagflat below main diagonal : 
 [[0 0 0 0]
 [1 0 0 0]
 [0 7 0 0]
 [0 0 6 0]]
1
2
3
4
5
6
7
8
# RANDOM NUMBERS
# randint(low, high=None, size=None, dtype=) Uniformly distributes integers in a given range
import numpy as np

np.random.seed(101) # enter an arbitrary number (called seed number)

arr1 = np.random.randint(0,100,10) # Returns random numbers from 'low'(inclusive) to 'high'(exclusive)
print(arr1)
1
[95 11 81 70 63 87 75  9 77 40]

Indexing:

Idexing is done in order to obtain slices of the main array. This can be done in the following ways-

  1. Basic slicing and indexing: using the form [start: stop: step]

  2. Advanced indexing: done by pure integer indexing or boolean indexing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Basic slicing and indexing

arr_1 = np.array([[[1, 2, 3], [4, 5, 6]],
                  [[7, 8, 9], [10, 11, 12]]])

print('Array 1:\n {}\n'.format(arr_1))

print('Indexing 1: \n {}\n'.format(arr_1[:, :, 2]))

print('Indexing 2: \n {}\n'.format(arr_1[:, :, 0]))


arr_2 = np.arange(0, 10)
print('Array 2: {}\n'.format(arr_2))

print('Indexing: \n {}\n'.format(arr_2[2:9:2]))

arr_3 = np.array([[0, 1, 2], [3, 4, 5],
                  [6, 7, 8], [9, 10, 11]])
print('Array 3:\n {}\n'.format(arr_3))

index_1 = arr_3[1:4, 0:2]
print('Indexing: {}'.format(index_1))

index_2 = arr_3[1:4, [2, 0]]
print('Indexing:\n {}\n'.format(index_2))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Array 1:
 [[[ 1  2  3]
  [ 4  5  6]]

 [[ 7  8  9]
  [10 11 12]]]

Indexing 1: 
 [[ 3  6]
 [ 9 12]]

Indexing 2: 
 [[ 1  4]
 [ 7 10]]

Array 2: [0 1 2 3 4 5 6 7 8 9]

Indexing: 
 [2 4 6 8]

Array 3:
 [[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]

Indexing: [[ 3  4]
 [ 6  7]
 [ 9 10]]
Indexing:
 [[ 5  3]
 [ 8  6]
 [11  9]]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Advanced slicing

import numpy as np

arr_1 = np.array([[3, 4, 7],
                  [5, 1, 8],
                  [2, 4, 7]])

print('Array 1:\n {}\n'.format(arr_1))

ind_1 = arr_1[[1, 2, 1],
              [2, 0, 1]]    # index inputs are column-wise
print('Index 1:\n {}\n'.format(ind_1))

# Type of rearrangement (See carefully)
imp = arr_1[np.array([[1, 2, 1],
                     [2, 0, 1]])]
print('Imp:\n {}'.format(imp))


# Boolean indexing

arr_2 = np.array([[2, 5, 8],
                  [1, 9, 0],
                  [3, 5, 4]])

print('Array 2:\n {}\n'.format(arr_2))

ind_2 = arr_2[arr_2 >= 3]
print('Indexing 2:\n {}\n'.format(ind_2))

arr_3 = np.array([10, 40, 80, 50, 100])
print('Indexing 3:\n {}'.format((arr_3[arr_3 % 40 == 0])**2))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Array 1:
 [[3 4 7]
 [5 1 8]
 [2 4 7]]

Index 1:
 [8 2 1]

Imp:
 [[[5 1 8]
  [2 4 7]
  [5 1 8]]

 [[2 4 7]
  [3 4 7]
  [5 1 8]]]
Array 2:
 [[2 5 8]
 [1 9 0]
 [3 5 4]]

Indexing 2:
 [5 8 9 3 5 4]

Indexing 3:
 [1600 6400]

Using .reshape(rows,columns) method

This method allows us to convert a given list into an array with required number of rows and columns.

1
2
3
4
5
6
7
8
9
10
# Using reshape() method

import numpy as np

arr = np.arange(0, 20)
print('Array 1: {}\n'.format(arr))

arr_2 = arr.reshape(4, 5)
print('Array 2:\n {}'.format(arr_2))

1
2
3
4
5
6
7
Array 1: [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]

Array 2:
 [[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]

Using numpy.nditer()

This method allows us to iterate over multi-dimensional arrays.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Using numpy.nditer() method
# https://youtu.be/XawR6CjAYV4

import numpy as np

arr = np.arange(0, 12).reshape(3, 4)
print('Reshaped Array 1:\n {}\n'.format(arr))

# Using a for loop
# for row in arr:
#  for cell in row:
#    print(cell)

# Both the codes are equivalent
# for row in arr.flatten():
#  print(row)

# Using nditer row-wise
for x in np.nditer(arr, order='C'):
    print(x)

print()

# Using nditer column-wise
for x in np.nditer(arr, order='F'):
    print(x)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Reshaped Array 1:
 [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

0
1
2
3
4
5
6
7
8
9
10
11

0
4
8
1
5
9
2
6
10
3
7
11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Using flags with nditer()

import numpy as np

a = np.arange(0, 12).reshape(3, 4)
print('Array:\n {}\n'.format(a))

# Doing this will allow you to print your entire column at once
for x in np.nditer(a, order='F', flags=['external_loop']):
    print(x)

print()

# Doing this will allow you to print your entire row at once
for x in np.nditer(a, order='C', flags=['external_loop']):
    print(x)

print()

# Using optional flags with op_flags option
# readwrite option is used to modify the elements of the array, and in this case, it gives us the square of all elements
for x in np.nditer(a, op_flags=['readwrite']):
    x[...] = x*x  # [...] is ellipsis.

print(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Array:
 [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

[0 4 8]
[1 5 9]
[ 2  6 10]
[ 3  7 11]

[ 0  1  2  3  4  5  6  7  8  9 10 11]

[[  0   1   4   9]
 [ 16  25  36  49]
 [ 64  81 100 121]]
1
2
3
4
5
6
7
8
9
10
11
12
13
# Iterating through two arrays using nditer()
# To do this, either both arrays should have the same shape, or one of the
# dimensions in one of the arrays should be 1

a = np.arange(0, 12).reshape(3, 4)
print('Array 1:\n {}\n'.format(a))

b = np.arange(3, 15, 4).reshape(3, 1)
print('Array 2:\n {}\n'.format(b))

for x, y in np.nditer([a, b]):
    print(x, y)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Array 1:
 [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Array 2:
 [[ 3]
 [ 7]
 [11]]

0 3
1 3
2 3
3 3
4 7
5 7
6 7
7 7
8 11
9 11
10 11
11 11

Binary Operations in Numpy

  1. numpy.bitwise_and(arr1,arr2): Computes the bitwise AND of two arrays, element wise

  2. numpy.bitwise_or(arr1,arr2): Computes the bitwise OR of two arrays, element wise

  3. numpy.bitwise_xor(arr1,arr2): Computes the bitwise XOR of two arrays, element wise

  4. numpy.invert(arr): Computes the bitwise NOT of an array, element wise

  5. numpy.left_shift(arr,bit_shift): Shifts the bits of an integer to the left and returns the corresponding decimal representation.

  6. numpy.right_shift(arr,bit_shift): Shifts the bits of an integer to the right and returns the corresponding decimal representation.

  7. numpy.unpackbits(array,axis): Unpacks elements of a uint8 array into a binary-valued output array.

  8. numpy.packbits(array,axis): Packs the elements of a binary-valued array into bits in a uint8 array.

  9. numpy.binary_repr(number,width): Gives the binary represntation of the array element. For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the two’s complement of the number is returned, with respect to that width.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# BINARY OPERATIONS

import numpy as np

arr_1 = np.array([2, 8, 125])
arr_2 = np.array([3, 3, 115])

print('Array 1: {}\n'.format(arr_1))
print('Array 2: {}\n'.format(arr_2))

# Bitswise AND Operation
arr_and = np.bitwise_and(arr_1, arr_2)
print('Bitwise AND: {}\n'.format(arr_and))

# Bitwise OR Operation
arr_or = np.bitwise_or(arr_1, arr_2)
print('Bitwise OR: {}\n'.format(arr_or))

# Bitwise XOR Operation
arr_xor = np.bitwise_xor(arr_1, arr_2)
print('Bitwise XOR: {}\n'.format(arr_xor))

1
2
3
4
5
6
7
8
9
Array 1: [  2   8 125]

Array 2: [  3   3 115]

Bitwise AND: [  2   0 113]

Bitwise OR: [  3  11 127]

Bitwise XOR: [ 1 11 14]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# BINARY OPERATIONS

import numpy as np

arr_1 = np.array([2, 8, 15])
print('Array 1: {}\n'.format(arr_1))

# Bitwise NOT Operation
arr_not = np.invert(arr_1)
print('Bitwise NOT: {}\n'.format(arr_not))

# Bit shift Operations
bit_shift_1 = np.array([3, 4, 5])
print('Bit shift array 1: {}\n'.format(bit_shift_1))

# Left shift
arr_left_shift = np.left_shift(arr_1, bit_shift_1)
print('Left shift: {}\n'.format(arr_left_shift))

print()

arr_2 = np.array([24, 48, 16])
print('Array 2: {}\n'.format(arr_2))

bit_shift_2 = np.array([3, 4, 2])
print('Bit shift array 2: {}\n'.format(bit_shift_2))

# Right shift
arr_right_shift = np.right_shift(arr_2, bit_shift_2)
print('Right shift: {}\n'.format(arr_right_shift))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Array 1: [ 2  8 15]

Bitwise NOT: [ -3  -9 -16]

Bit shift array 1: [3 4 5]

Left shift: [ 16 128 480]


Array 2: [24 48 16]

Bit shift array 2: [3 4 2]

Right shift: [3 3 4]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# BINARY OPERATIONS

import numpy as np

in_arr = [5, -8]

print()

print("Input array : ", in_arr)

# Without using width parameter
out_num = np.binary_repr(in_arr[0])
print("Binary representation of 5")
print("Without using width parameter : ", out_num)

# Using width parameter
out_num = np.binary_repr(in_arr[0], width=5)
print("Using width parameter: ", out_num)

print("\nBinary representation of -8")

# Without using width parameter
out_num = np.binary_repr(in_arr[1])
print("Without using width parameter : ", out_num)

# Using width parameter
out_num = np.binary_repr(in_arr[1], width=5)
print("Using width parameter : ", out_num)

1
2
3
4
5
6
7
8
Input array :  [5, -8]
Binary representation of 5
Without using width parameter :  101
Using width parameter:  00101

Binary representation of -8
Without using width parameter :  -1000
Using width parameter :  11000

Linear Algebra using Numpy

The Linear Algebra module of NumPy offers various methods to apply linear algebra on any numpy array. One can find:

  1. rank, determinant, trace, etc. of an array.
  2. eigen values of matrices
  3. matrix and vector products (dot, inner, outer,etc. product), matrix exponentiation
  4. solve linear or tensor equations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# LINEAR ALGEBRA

import numpy as np

A = np.array([[6, 1, 1],
              [4, -2, 5],
              [2, 8, 7]])

# Rank of a matrix
print("Rank of A:", np.linalg.matrix_rank(A))

# Trace of matrix A
print("\nTrace of A:", np.trace(A))

# Determinant of a matrix
print("\nDeterminant of A:", np.linalg.det(A))

# Inverse of matrix A
print("\nInverse of A:\n", np.linalg.inv(A))

print("\nMatrix A raised to power 3:\n",
      np.linalg.matrix_power(A, 3))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Rank of A: 3

Trace of A: 11

Determinant of A: -306.0

Inverse of A:
 [[ 0.17647059 -0.00326797 -0.02287582]
 [ 0.05882353 -0.13071895  0.08496732]
 [-0.11764706  0.1503268   0.05228758]]

Matrix A raised to power 3:
 [[336 162 228]
 [406 162 469]
 [698 702 905]]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# LINEAR ALGEBRA

# Matrix and Vector products

import numpy as np


# Using numpy.dot(): returns the dot product of vectors a and b

# Scalars
product = np.dot(5, 4)
print("Dot Product of scalar values  : ", product)

# 1D array
vector_a = 2 + 3j
vector_b = 4 + 5j

product = np.dot(vector_a, vector_b)
print("Dot Product  : ", product)

# Using numpy.vdot(): Returns the dot product of vectors a and b. If first
# argument is complex the complex conjugate of the first argument is used
# for the calculation of the dot product

vector_a = 2 + 3j
vector_b = 4 + 5j

product = np.vdot(vector_a, vector_b)
print("VDot Product  : ", product)

1
2
3
Dot Product of scalar values  :  20
Dot Product  :  (-7+22j)
VDot Product  :  (23-2j)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# LINEAR ALGEBRA

# Solving equations

# numpy.linalg.solve(): Solves a system of linear scalar equations.
# Computes the “exact” solution, x, of the linear matrix equation ax = b.

import numpy as np

a = np.array([[1, 2], [3, 4]])

b = np.array([8, 18])

print("Solution of linear equations:", np.linalg.solve(a, b))

1
Solution of linear equations: [2. 3.]

Using numpy.sum():

numpy.sum(arr, axis, dtype, out) : This function returns the sum of array elements over the specified axis.

out : Different array in which we want to place the result. The array must have same dimensions as expected output. Default is None.

Using numpy.add():

numpy.add(arr1, arr2, /, out=None) : This function is used when we want to compute the addition of two array. It adds arguments element-wise.

If shape of two arrays are not same, they must be broadcastable to a common shape.

Broadcastable arrays - should have same dimensions or the dimension of one of the arrays should be 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Using numpy.sum()

import numpy as np

# 2D array
arr = [[14, 17, 12, 33, 44],
       [15, 6, 27, 8, 19],
       [23, 2, 54, 1, 4, ]]

print("\nSum of arr : ", np.sum(arr))

print("\nSum of arr : ", np.sum(arr, axis=0))

print("\nSum of arr : ", np.sum(arr, axis=1))

1
2
3
4
5
Sum of arr :  279

Sum of arr :  [52 25 93 42 67]

Sum of arr :  [120  75  84]
1
2
3
4
5
6
7
8
9
10
11
12
13
# Using numpy.add()

import numpy as np

in_arr1 = np.array([[2, -7, 5], [-6, 2, 0]])
in_arr2 = np.array([[5, 8, -5], [3, 6, 9]])

print("1st Input array : \n", in_arr1)
print("2nd Input array : \n", in_arr2)

out_arr = np.add(in_arr1, in_arr2)
print("output added array : \n", out_arr)

1
2
3
4
5
6
7
8
9
1st Input array : 
 [[ 2 -7  5]
 [-6  2  0]]
2nd Input array : 
 [[ 5  8 -5]
 [ 3  6  9]]
output added array : 
 [[ 7  1  0]
 [-3  8  9]]

numpy.concatenate()

numpy.concatenate() function concatenate a sequence of arrays along an existing axis.

It is used to join two or more arrays

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Concatenate

import numpy as np

arr1 = np.array([[2, 4], [6, 8]])
arr2 = np.array([[3, 5], [7, 9]])
print('Array 1: \n', arr1)
print('Array 2: \n', arr2)
gfg_1 = np.concatenate((arr1, arr2), axis=1)
print('Horizontally: \n', gfg_1)

gfg_2 = np.concatenate((arr1, arr2), axis=0)
print('Vertically: \n', gfg_2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Array 1: 
 [[2 4]
 [6 8]]
Array 2: 
 [[3 5]
 [7 9]]
Horizontally: 
 [[2 4 3 5]
 [6 8 7 9]]
Vertically: 
 [[2 4]
 [6 8]
 [3 5]
 [7 9]]

numpy.append()

numpy.append(array, values, axis = None) : appends values along the mentioned axis at the end of the array.

It is used to add items/elements/arrays.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# numpy.append()

import numpy as np

arr = np.array([[2, 3, 1],
                [4, 8, 1]])
print('Original Array: \n', arr)
mylist = [[3, 1, 0], [4, 5, 1]]  # Dimensions should be the same.
print('List: ', mylist)

new_arr = np.append(arr, mylist, axis=1)
print('\nAppended array: \n', new_arr)

print()

arr_2 = np.append(arr, [[3, 4, 1], [1, 4, 0]], axis=0)
print(arr_2)
# Error when only one list is given.

1
2
3
4
5
6
7
8
9
10
11
12
13
Original Array: 
 [[2 3 1]
 [4 8 1]]
List:  [[3, 1, 0], [4, 5, 1]]

Appended array: 
 [[2 3 1 3 1 0]
 [4 8 1 4 5 1]]

[[2 3 1]
 [4 8 1]
 [3 4 1]
 [1 4 0]]

Sorting

Arranging data in a specific order. We can sort a numpy array in the following ways:

  1. numpy.sort(): Returns sorted copy of the array

  2. numpy.argsort(): Returns indices that would sort an array

  3. numpy.sort_complex(): Sorts an array with real part first, then the imaginary part

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# SORTING

# Using numpy.sort()

import numpy as np

a = np.array([[12, 15], [10, 1]])
print('Array 1: \n{}\n'.format(a))
arr1 = np.sort(a, axis=0)
print("Column wise (axis=0) : \n", arr1)

a = np.array([[10, 15], [12, 1]])
print('\nArray 2: \n{}\n'.format(a))
arr2 = np.sort(a, axis=1)        # Axis=1 and Axis=-1 are the same
print("Row wise (axis=1/-1) : \n", arr2)

arr1 = np.sort(a, axis=None)
print("\nAlong none axis : \n", arr1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Array 1: 
[[12 15]
 [10  1]]

Column wise (axis=0) : 
 [[10  1]
 [12 15]]

Array 2: 
[[10 15]
 [12  1]]

Row wise (axis=1/-1) : 
 [[10 15]
 [ 1 12]]

Along none axis : 
 [ 1 10 12 15]
1
2
3
4
5
6
7
8
9
10
11
12
# SORTING

# Using numpy.argsort()

import numpy as np

a = np.array([9, 3, 1, 7, 4, 3, 6])
print('Original array:\n', a)

b = np.argsort(a)
print('Sorted indices of original array->', b)

1
2
3
Original array:
 [9 3 1 7 4 3 6]
Sorted indices of original array-> [2 1 5 4 6 3 0]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# SORTING

import numpy as np

arr_1 = np.array([4, 8, 1, 2, 9])
names = np.array(['A', 'B', 'C', 'D', 'E'])

# Low to High
sort_1 = np.sort(arr_1)
print('Sorted Array 1: {}\n'.format(sort_1))

# High to Low
sort_2 = np.sort(arr_1)[::-1]
print('Sorted Array 2: {}\n'.format(sort_2))

# Sorting names
sort_names = names[np.argsort(arr_1)[::-1]]
print('Sorted Names: {}'.format(sort_names))

1
2
3
4
5
Sorted Array 1: [1 2 4 8 9]

Sorted Array 2: [9 8 4 2 1]

Sorted Names: ['E' 'B' 'A' 'D' 'C']

Searching

Searching is an operation or a technique that helps finds the place of a given element or value in the list. This can be done in some of the following ways:

  1. numpy.argmax(): Returns indices of the max element of the array in a particular axis.

  2. numpy.nanargmax(): Returns indices of the max element of the array in a particular axis ignoring NaNs.The results cannot be trusted if a slice contains only NaNs and Infs.

  3. numpy.argmin(): Returns the indices of the minimum values along an axis.

  4. numpy.where(): Returns the indices of elements in an input array where the given condition is satisfied.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# SEARCHING

import numpy as np

array = np.arange(12).reshape(3, 4)
print("INPUT ARRAY : \n", array)

print("\nMax element : ", np.argmax(array))

print("Indices of Max element: ", np.argmax(array, axis=0))
print("Indices of Max element: ", np.argmax(array, axis=1))
print("Indices of min element : ", np.argmin(array, axis=0))

print()

# numpy.where()

a = np.array([[1, 2, 3], [4, 5, 6]])
print('Array 2: \n', a)

print('Indices of elements <4')

b = np.where(a < 4)
print(b)

print("Elements which are <4")
print(a[b])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
INPUT ARRAY : 
 [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Max element :  11
Indices of Max element:  [2 2 2 2]
Indices of Max element:  [3 3 3]
Indices of min element :  [0 0 0 0]

Array 2: 
 [[1 2 3]
 [4 5 6]]
Indices of elements <4
(array([0, 0, 0]), array([0, 1, 2]))
Elements which are <4
[1 2 3]

Counting

numpy.count_nonzero() : Counts the number of non-zero values in the array .

1
2
3
4
5
6
7
8
9
import numpy as np

# Counting a number of non-zero values
a = np.count_nonzero([[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]])
b = np.count_nonzero([[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]], axis=0)

print("Number of nonzero values is :", a)
print("Number of nonzero values is :", b)

1
2
Number of nonzero values is : 5
Number of nonzero values is : [1 1 1 1 1]
This post is licensed under CC BY 4.0 by the author.