Arrays in Python
February 13, 2018
1 Array
• Collection of homogeneous values
• Used to implement other data structures such as stacks, queues, linked lists etc...
• One of the common application is Processing of matrices.
• In Python,arrays are not fundamental data type
• To use arrays, user needs to
– import the array module
– import numpy module
1.1 Importing Array Module
In [1]: from array import *
1.1.1 Declaring Arrays
arrayname = array(typecode, [list of elements])
In [3]: d = array('u',['h','e','l','l','o'])
print(d)
array('u', 'hello')
1.1.2 Creating Array
In [2]: from array import *
my_array = array('i',[11,21,31,41])
print("Display the array :",my_array)
print()
print("Array Elements :",end='')
for i in my_array:
print(i,end=' ')
Display the array : array('i', [11, 21, 31, 41])
Array Elements :11 21 31 41
1
1.1.3 Reading input from the user as a list of integers
In [4]: list_input = [int(x) for x in input("Enter array elements : ").strip().split(' ')]
print()
print("Entered elements :", list_input)
print()
my_array2 = array('i', list_input)
print("Display the array :",my_array2)
print()
Enter array elements : 11 12 13
Entered elements : [11, 12, 13]
Display the array : array('i', [11, 12, 13])
1.1.4 Accessing an element of an array
In [7]: print("First element : %d" % my_array[0])
size = len(my_array)
print("Sum of first and last element : %d" % (my_array[0]+my_array[size-1]))
First element : 11
Sum of first and last element : 52
1.1.5 len(arrayname)
• Number of elements in an Array
In [8]: size = len(my_array)
print("No. of elements : %d" % size)
No. of elements : 4
1.1.6 array.insert(pos,item)
• Adding element in the middle of the array
In [9]: size = len(my_array2)
mid = int(size/2)
print("index of middle element : %d"% mid)
print()
2
x = int(input("Enter the value to be inserted in the middle :").strip())
print()
print("Before insert(pos,item) :", my_array2)
print()
my_array2.insert(mid,x)
print("Before insert(pos,item) :", my_array2)
index of middle element : 1
Enter the value to be inserted in the middle :55
Before insert(pos,item) : array('i', [11, 12, 13])
Before insert(pos,item) : array('i', [11, 55, 12, 13])
1.1.7 array.append(item)
• Adding new element to the end of the array
In [10]: y = int(input("Enter the value to be added to the end :").strip())
print()
print("Before append(item) :", my_array2)
print()
my_array2.append(y)
print("After append(item) :", my_array2)
Enter the value to be added to the end :99
Before append(item) : array('i', [11, 55, 12, 13])
After append(item) : array('i', [11, 55, 12, 13, 99])
1.1.8 array.extend(array2)
• Extending the existing array from another array
In [11]: print("Before extend(array2) :", my_array)
print()
my_array.extend(my_array2)
print("Extended array:", my_array)
3
Before extend(array2) : array('i', [11, 21, 31, 41])
Extended array: array('i', [11, 21, 31, 41, 11, 55, 12, 13, 99])
1.1.9 array.fromlist(list)
• Extending an array from list
In [ ]: print("Before fromlist(list) :", my_array)
print()
new_list = [int(x) for x in input('Enter elements comma separated: ').strip().split(',')
print()
my_array.fromlist(new_list)
print("Extended Array from list :",my_array)
Before fromlist(list) : [[11 23]
[33 44]]
1.1.10 array.typecode
• Print typecode of the array
In [14]: print(my_array.typecode)
i
1.1.11 array.itemsize
• Print length of one array item in bytes
In [15]: print("Item size : %d bytes" % my_array.itemsize)
Item size : 4 bytes
1.1.12 array.byteswap()
• Swaps the characters bytewise
In [16]: print('before byteswap() : ', my_array)
print()
my_array.byteswap()
4
print('after byteswap() : ',my_array)
print()
# Repeat byteswap to retrieve the original array
my_array.byteswap()
print('after byteswap() called twice : ',my_array)
before byteswap() : array('i', [11, 21, 31, 41, 11, 55, 12, 13, 99, 1, 2])
after byteswap() : array('i', [184549376, 352321536, 520093696, 687865856, 184549376, 922746880
after byteswap() called twice : array('i', [11, 21, 31, 41, 11, 55, 12, 13, 99, 1, 2])
1.1.13 array.count(item)
• Occurance of a item in array
In [17]: my_array.count(21)
Out[17]: 1
1.1.14 array.pop(index)
• Deleting element
In [18]: print("Before pop(index): ",my_array)
print()
#Pop element @ index,i from the array using array.pop(index)
my_array.pop(2)
print("After pop(index): ",my_array)
print()
#Pop last element using array.pop()
my_array.pop()
print("After pop(): ",my_array)
Before pop(index): array('i', [11, 21, 31, 41, 11, 55, 12, 13, 99, 1, 2])
After pop(index): array('i', [11, 21, 41, 11, 55, 12, 13, 99, 1, 2])
After pop(): array('i', [11, 21, 41, 11, 55, 12, 13, 99, 1])
5
1.1.15 array.reverse()
• Reverse an array
In [19]: print("Before reveral: ",my_array)
print()
my_array.reverse()
print("After reveral: ",my_array)
Before reveral: array('i', [11, 21, 41, 11, 55, 12, 13, 99, 1])
After reveral: array('i', [1, 99, 13, 12, 55, 11, 41, 21, 11])
1.1.16 array.remove(item)
• Remove the first occurance of an item from the array
In [20]: print("Before remove(x) :", my_array)
print()
x = int(input("Enter the item to be removed ").strip())
if x in my_array:
my_array.remove(x)
print("After removal :", my_array)
else:
print("Item not in array")
Before remove(x) : array('i', [1, 99, 13, 12, 55, 11, 41, 21, 11])
Enter the item to be removed 55
After removal : array('i', [1, 99, 13, 12, 11, 41, 21, 11])
1.1.17 array.tolist()
• Creating a list from array
In [21]: print("Array before tolist() :", my_array)
print()
l = my_array.tolist()
print("Array after tolist() ", my_array)
print()
print("Created list : ", l)
6
Array before tolist() : array('i', [1, 99, 13, 12, 11, 41, 21, 11])
Array after tolist() array('i', [1, 99, 13, 12, 11, 41, 21, 11])
Created list : [1, 99, 13, 12, 11, 41, 21, 11]
1.2 Using NumPy module
• Numeric / Numerical Python
• Full fledge Python package
• Contains objects of multidimensional array and routines for processing them.
• Advantages of Python with NumPy
1. Efficient computation of multi-dimensional arrays
2. Fast precompiled functions for mathematical and numerical routines
3. NumPy is designed for scientific computation
1.2.1 array() in NumPy
• Creating ndarray objects
In [22]: import numpy as np
arr = np.array([1,2,3,4])
print('Array 1 : ',arr)
print('datatype : ',arr.dtype)
print()
arr2 = np.array([1.,2,3,4])
print('Array 2 : ',arr2)
print('datatype : ',arr2.dtype)
print()
Array 1 : [1 2 3 4]
datatype : int64
Array 2 : [ 1. 2. 3. 4.]
datatype : float64
Program : Convert Celsius to Farenheit
In [23]: import numpy as np
c_array = np.array([21.3,54.1,36.2,45.6])
print("Celsius values : ", c_array)
print()
7
f_array = c_array *9/5 + 32
print("Farenheit values :", f_array)
Celsius values : [ 21.3 54.1 36.2 45.6]
Farenheit values : [ 70.34 129.38 97.16 114.08]
1.2.2 arange(x)
• Creating ndarray object
In [24]: import numpy as np
arr = np.arange(20)
print('Array : ',arr)
Array : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
1.2.3 Creating 2D arrays
In [25]: import numpy as np
my_array = np.array([[11,23],[33,44]])
print('2D array')
print(my_array)
2D array
[[11 23]
[33 44]]
Program : Matrix Operations
In [26]: import numpy as np
a = np.array([[1,1],[1,1]])
b = np.array([[1,1],[1,1]])
c = np.matrix('1,1;1,1')
d = np.matrix('1,1,1;1,1,1')
print("Matrix Addition")
print(a+b)
print("Matrix Multiplication of equal order")
print(a*b)
print("Matrix Multiplication of unequal order")
print(c*d)
Matrix Addition
[[2 2]
[2 2]]
8
Matrix Multiplication of equal order
[[1 1]
[1 1]]
Matrix Multiplication of unequal order
[[2 2 2]
[2 2 2]]
1.2.4 matrix() in NumPy
• Creating a Matrix
In [27]: import numpy as np
my_matrix = np.matrix('1,2,3;4,5,6;7,8,9')
print("Matrix")
print(my_matrix)
Matrix
[[1 2 3]
[4 5 6]
[7 8 9]]
1.2.5 Basic Slicing
Array Slicing
• Using slice object
In [28]: import numpy as np
arr = np.arange(20)
print("Original array :", arr)
print()
#Creating slice object using slice(start,stop,step)in NumPy
slice_arr = slice(1,20,2)
#Slice object is passed to the array to create a new array
s_arr = arr[slice_arr]
print('Sliced array :',s_arr)
print()
print('Origianl array : ', arr)
Original array : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
Sliced array : [ 1 3 5 7 9 11 13 15 17 19]
9
Origianl array : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
• Using colon separators
In [29]: import numpy as np
arr = np.arange(20)
print("Original array :", arr)
print()
#Slice object is passed to the array to create a new array
s_arr = arr[1:20:2]
print('Sliced array :',s_arr)
print()
print('Origianl array : ', arr)
print()
print('Reversing Array using slicing :', arr[::-1])
Original array : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
Sliced array : [ 1 3 5 7 9 11 13 15 17 19]
Origianl array : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
Reversing Array using slicing : [19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0]
Matrix Slicing
• using colon separators
In [30]: import numpy as np
x = np.matrix('11,12,13,14;21,22,23,24;31,32,33,34;41,42,43,44')
print('Matrix')
print(x)
print()
print(x[1:3])
print()
Matrix
[[11 12 13 14]
[21 22 23 24]
[31 32 33 34]
[41 42 43 44]]
10
[[21 22 23 24]
[31 32 33 34]]
• using ellipsis(...)
– for making tuple selection of the same length as array dimension
In [31]: import numpy as np
x = np.matrix('11,12,13,14;21,22,23,24;31,32,33,34;41,42,43,44')
print(' Original Matrix')
print(x)
print()
#Column selection
print('Column 1 selection :')
print(x[...,1])
print()
#Column slicing
print('Slicing from Column 1 onwards :')
print(x[...,1:])
print()
#Row Selection
print('Row 1 selection :')
print(x[1,...])
Original Matrix
[[11 12 13 14]
[21 22 23 24]
[31 32 33 34]
[41 42 43 44]]
Column 1 selection :
[[12]
[22]
[32]
[42]]
Slicing from Column 1 onwards :
[[12 13 14]
[22 23 24]
[32 33 34]
[42 43 44]]
Row 1 selection :
[[21 22 23 24]]
11
1.2.6 Advanced indexing
• Two kinds
1. Integer Indexing
– based on N Dimensional index
– any arbitrary element in an array can be selected
2. Boolean Indexing
– used when the result is meant to be the result of boolean operations
Integer Indexing
In [32]: import numpy as np
a = np.matrix('1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16')
print('Original Matrix')
print(a)
print()
# row contains row indices and col contains column indices for elements in the corners
row = np.array([[0,0],[3,3]])
col = np.array([[0,3],[0,3]])
# row and col indices are combined to form a new ndarray object
b = a[row,col]
print(b)
print()
# row contains row indices and col contains column indices for elements in the middle
row1 = np.array([[1,1],[2,2]])
col1 = np.array([[1,2],[1,2]])
# row and col indices are combined to form a new ndarray object
b1 = a[row1,col1]
print(b1)
print()
# row contains row indices and col contains column indices for elements in the middle e
row2 = np.array([[1,1],[2,2]])
col2 = np.array([[0,3],[0,3]])
# row and col indices are combined to form a new ndarray object
b2 = a[row2,col2]
print(b2)
Original Matrix
[[ 1 2 3 4]
12
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
[[ 1 4]
[13 16]]
[[ 6 7]
[10 11]]
[[ 5 8]
[ 9 12]]
Combining Basic and Advanced Indexing
In [33]: import numpy as np
a = np.matrix('1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16')
print('Original Matrix')
print(a)
print()
s1 = a[1:,:3]
print(s1)
print()
#Advanced Slicing for column
ad = a[1:3,[1,2]]
print(ad)
Original Matrix
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
[[ 5 6 7]
[ 9 10 11]
[13 14 15]]
[[ 6 7]
[10 11]]
Boolean Indexing
In [34]: import numpy as np
a = np.matrix('1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16')
13
print('Original Matrix')
print(a)
print()
#Printing elements less than 15
s = arr[arr<15]
print('Array with <15 items :',s)
Original Matrix
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
Array with <15 items : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
In [35]: import numpy as np
a = np.array([20,20+1j,56,12-1j])
print(a)
print(a.dtype)
#To extract complex elements in the existing array
c = a[np.iscomplex(a)]
print('Complex array : ',c)
[ 20.+0.j 20.+1.j 56.+0.j 12.-1.j]
complex128
Complex array : [ 20.+1.j 12.-1.j]
1.2.7 Array Manipulations
• NumPy contains different routines and functions for processing multi-dimensional arrays
• Some of the commonly used functions are:
1. reshape(newshape) & resize(array,newshape)
2. flatten(order) & ravel(order)
3. transpose(array) & T
4. concatenate((arr1,arr2),axis)
5. split([indices],axis)
reshape(newshape) and resize(newshape)
• where newshape should be compatibe with original shape
In [36]: import numpy as np
a = np.arange(20)
14
print('Original Array', a)
print()
a1 = a.reshape(4,5)
print('Reshaped Array (4*5)')
print(a1)
print()
a2 = np.resize(a,(2,10))
print('Reshaped Array (2*10)')
print(a2)
Original Array [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
Reshaped Array (4*5)
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
Reshaped Array (2*10)
[[ 0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]]
flatten(order) and ravel(order)
• where order - row major (’C’), col major (’F’)
In [37]: a2 = a1.flatten(order = 'F')
print('Flattened Matrix in col major order :')
print(a2)
print()
a3 = a1.ravel(order = 'C')
print('Flattened Matrix in row major order :')
print(a3)
Flattened Matrix in col major order :
[ 0 5 10 15 1 6 11 16 2 7 12 17 3 8 13 18 4 9 14 19]
Flattened Matrix in row major order :
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
transpose()
In [38]: print('Original Matrix')
print(a1)
15
print()
t = a1.transpose()
print('Transpose Matrix')
print(t)
print()
t1 = t.T
print('Transpose of transposed matrix')
print(t1)
print()
Original Matrix
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
Transpose Matrix
[[ 0 5 10 15]
[ 1 6 11 16]
[ 2 7 12 17]
[ 3 8 13 18]
[ 4 9 14 19]]
Transpose of transposed matrix
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
concatenate((arr1, arr2, ... ), axis)
• concatenates arrays of same shape along a specified axis
• arr1, arr2, ... : sequence of arrays of same type
• axis : axis along which arrays must be joined
– 0 (x-axis ) / 1 (y-axis)
In [39]: a1 = np.array([[11,12,13],[14,15,16],[17,18,19]])
print('Original Matrix 1')
print(a1)
print()
a2=a1.T
print('Original Matrix 2')
print(a2)
16
print()
c1 = np.concatenate((a1,a2))
print('Concatenated Matrix at axis = 0 (x-axis)')
print(c1)
print()
c2 = np.concatenate((a1,a2),axis = 1)
print('Concatenated Matrix at axis = 1 (y-axis)')
print(c2)
print()
Original Matrix 1
[[11 12 13]
[14 15 16]
[17 18 19]]
Original Matrix 2
[[11 14 17]
[12 15 18]
[13 16 19]]
Concatenated Matrix at axis = 0 (x-axis)
[[11 12 13]
[14 15 16]
[17 18 19]
[11 14 17]
[12 15 18]
[13 16 19]]
Concatenated Matrix at axis = 1 (y-axis)
[[11 12 13 11 14 17]
[14 15 16 12 15 18]
[17 18 19 13 16 19]]
split(arr, [indices], axis)
• breaks the array into subarrays along a specified axis
• arr : array to be divided
• indices : integer specifying the number of equal sized sub-arrays
• axis : along which the array is split
– 0 (x-axis) / 1 (y-axis)
In [40]: a1 = np.array([[11,12,13],[14,15,16],[17,18,19]])
print('Original Matrix 1')
print(a1)
17
print()
#split at axis = 0 (x-axis)
x,y,z = np.split(a1,[1,2])
print('split at axis = 0 (x-axis)')
print('Subarray 1 :', x)
print()
print('Subarray 2 :', y)
print()
print('Subarray 3 :', z)
#split at axis = 1 (y-axis)
x,y,z = np.split(a1,[1,2], axis =1)
print('split at axis = 1 (y-axis)')
print('Subarray 1 :')
print(x)
print()
print('Subarray 2 :')
print(y)
print()
print('Subarray 3 :')
print(z)
Original Matrix 1
[[11 12 13]
[14 15 16]
[17 18 19]]
split at axis = 0 (x-axis)
Subarray 1 : [[11 12 13]]
Subarray 2 : [[14 15 16]]
Subarray 3 : [[17 18 19]]
split at axis = 1 (y-axis)
Subarray 1 :
[[11]
[14]
[17]]
Subarray 2 :
[[12]
[15]
[18]]
Subarray 3 :
[[13]
[16]
18
[19]]
insert(arr, pos, values, axis)
• arr : array
• pos : index before which insertion is to be made
• values : array of values to be inserted along axis
• axis : 0 (x-axis) / 1 (y-axis)
In [41]: arr1 = np.array([[11,12,13],[21,22,23]])
list1 = [31,32,33]
arr2 = np.insert(arr1,1,list1,0)
print(arr2)
print()
list2 = [41,42]
arr3 = np.insert(arr1,2,list2,1)
print(arr3)
[[11 12 13]
[31 32 33]
[21 22 23]]
[[11 12 41 13]
[21 22 42 23]]
append(arr,values,axis)
• arr : array
• values: list of values to be appended
• axis : 0 (x-axis)/ 1 (y-axis) along which append operation is to be performed
In [42]: arr1 = np.arange(6)
print(arr1.ndim)
print(arr1)
list1 = [int(x) for x in input("Enter the 3 numbers separated by comma :").strip().spli
print(list1)
arr2 = np.append(arr1,list1,0)
print(arr2)
1
[0 1 2 3 4 5]
Enter the 3 numbers separated by comma :9,6,7
[9, 6, 7]
[0 1 2 3 4 5 9 6 7]
19
delete(arr, obj, axis)
• arr : array
• obj : object to be deleted
• axis : 0 (x-axis) / 1 (y-axis) along which deletion is to be performed
In [43]: arr1 = np.arange(25).reshape(5,5)
arr2 = np.delete(arr1,1,1)
arr3 = np.delete(arr1,2,0)
print("arr1 : ")
print(arr1)
print("arr2 : ")
print(arr2)
print("arr3 : ")
print(arr3)
arr1 :
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
arr2 :
[[ 0 2 3 4]
[ 5 7 8 9]
[10 12 13 14]
[15 17 18 19]
[20 22 23 24]]
arr3 :
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[15 16 17 18 19]
[20 21 22 23 24]]
20

Arrays in python

  • 1.
    Arrays in Python February13, 2018 1 Array • Collection of homogeneous values • Used to implement other data structures such as stacks, queues, linked lists etc... • One of the common application is Processing of matrices. • In Python,arrays are not fundamental data type • To use arrays, user needs to – import the array module – import numpy module 1.1 Importing Array Module In [1]: from array import * 1.1.1 Declaring Arrays arrayname = array(typecode, [list of elements]) In [3]: d = array('u',['h','e','l','l','o']) print(d) array('u', 'hello') 1.1.2 Creating Array In [2]: from array import * my_array = array('i',[11,21,31,41]) print("Display the array :",my_array) print() print("Array Elements :",end='') for i in my_array: print(i,end=' ') Display the array : array('i', [11, 21, 31, 41]) Array Elements :11 21 31 41 1
  • 2.
    1.1.3 Reading inputfrom the user as a list of integers In [4]: list_input = [int(x) for x in input("Enter array elements : ").strip().split(' ')] print() print("Entered elements :", list_input) print() my_array2 = array('i', list_input) print("Display the array :",my_array2) print() Enter array elements : 11 12 13 Entered elements : [11, 12, 13] Display the array : array('i', [11, 12, 13]) 1.1.4 Accessing an element of an array In [7]: print("First element : %d" % my_array[0]) size = len(my_array) print("Sum of first and last element : %d" % (my_array[0]+my_array[size-1])) First element : 11 Sum of first and last element : 52 1.1.5 len(arrayname) • Number of elements in an Array In [8]: size = len(my_array) print("No. of elements : %d" % size) No. of elements : 4 1.1.6 array.insert(pos,item) • Adding element in the middle of the array In [9]: size = len(my_array2) mid = int(size/2) print("index of middle element : %d"% mid) print() 2
  • 3.
    x = int(input("Enterthe value to be inserted in the middle :").strip()) print() print("Before insert(pos,item) :", my_array2) print() my_array2.insert(mid,x) print("Before insert(pos,item) :", my_array2) index of middle element : 1 Enter the value to be inserted in the middle :55 Before insert(pos,item) : array('i', [11, 12, 13]) Before insert(pos,item) : array('i', [11, 55, 12, 13]) 1.1.7 array.append(item) • Adding new element to the end of the array In [10]: y = int(input("Enter the value to be added to the end :").strip()) print() print("Before append(item) :", my_array2) print() my_array2.append(y) print("After append(item) :", my_array2) Enter the value to be added to the end :99 Before append(item) : array('i', [11, 55, 12, 13]) After append(item) : array('i', [11, 55, 12, 13, 99]) 1.1.8 array.extend(array2) • Extending the existing array from another array In [11]: print("Before extend(array2) :", my_array) print() my_array.extend(my_array2) print("Extended array:", my_array) 3
  • 4.
    Before extend(array2) :array('i', [11, 21, 31, 41]) Extended array: array('i', [11, 21, 31, 41, 11, 55, 12, 13, 99]) 1.1.9 array.fromlist(list) • Extending an array from list In [ ]: print("Before fromlist(list) :", my_array) print() new_list = [int(x) for x in input('Enter elements comma separated: ').strip().split(',') print() my_array.fromlist(new_list) print("Extended Array from list :",my_array) Before fromlist(list) : [[11 23] [33 44]] 1.1.10 array.typecode • Print typecode of the array In [14]: print(my_array.typecode) i 1.1.11 array.itemsize • Print length of one array item in bytes In [15]: print("Item size : %d bytes" % my_array.itemsize) Item size : 4 bytes 1.1.12 array.byteswap() • Swaps the characters bytewise In [16]: print('before byteswap() : ', my_array) print() my_array.byteswap() 4
  • 5.
    print('after byteswap() :',my_array) print() # Repeat byteswap to retrieve the original array my_array.byteswap() print('after byteswap() called twice : ',my_array) before byteswap() : array('i', [11, 21, 31, 41, 11, 55, 12, 13, 99, 1, 2]) after byteswap() : array('i', [184549376, 352321536, 520093696, 687865856, 184549376, 922746880 after byteswap() called twice : array('i', [11, 21, 31, 41, 11, 55, 12, 13, 99, 1, 2]) 1.1.13 array.count(item) • Occurance of a item in array In [17]: my_array.count(21) Out[17]: 1 1.1.14 array.pop(index) • Deleting element In [18]: print("Before pop(index): ",my_array) print() #Pop element @ index,i from the array using array.pop(index) my_array.pop(2) print("After pop(index): ",my_array) print() #Pop last element using array.pop() my_array.pop() print("After pop(): ",my_array) Before pop(index): array('i', [11, 21, 31, 41, 11, 55, 12, 13, 99, 1, 2]) After pop(index): array('i', [11, 21, 41, 11, 55, 12, 13, 99, 1, 2]) After pop(): array('i', [11, 21, 41, 11, 55, 12, 13, 99, 1]) 5
  • 6.
    1.1.15 array.reverse() • Reversean array In [19]: print("Before reveral: ",my_array) print() my_array.reverse() print("After reveral: ",my_array) Before reveral: array('i', [11, 21, 41, 11, 55, 12, 13, 99, 1]) After reveral: array('i', [1, 99, 13, 12, 55, 11, 41, 21, 11]) 1.1.16 array.remove(item) • Remove the first occurance of an item from the array In [20]: print("Before remove(x) :", my_array) print() x = int(input("Enter the item to be removed ").strip()) if x in my_array: my_array.remove(x) print("After removal :", my_array) else: print("Item not in array") Before remove(x) : array('i', [1, 99, 13, 12, 55, 11, 41, 21, 11]) Enter the item to be removed 55 After removal : array('i', [1, 99, 13, 12, 11, 41, 21, 11]) 1.1.17 array.tolist() • Creating a list from array In [21]: print("Array before tolist() :", my_array) print() l = my_array.tolist() print("Array after tolist() ", my_array) print() print("Created list : ", l) 6
  • 7.
    Array before tolist(): array('i', [1, 99, 13, 12, 11, 41, 21, 11]) Array after tolist() array('i', [1, 99, 13, 12, 11, 41, 21, 11]) Created list : [1, 99, 13, 12, 11, 41, 21, 11] 1.2 Using NumPy module • Numeric / Numerical Python • Full fledge Python package • Contains objects of multidimensional array and routines for processing them. • Advantages of Python with NumPy 1. Efficient computation of multi-dimensional arrays 2. Fast precompiled functions for mathematical and numerical routines 3. NumPy is designed for scientific computation 1.2.1 array() in NumPy • Creating ndarray objects In [22]: import numpy as np arr = np.array([1,2,3,4]) print('Array 1 : ',arr) print('datatype : ',arr.dtype) print() arr2 = np.array([1.,2,3,4]) print('Array 2 : ',arr2) print('datatype : ',arr2.dtype) print() Array 1 : [1 2 3 4] datatype : int64 Array 2 : [ 1. 2. 3. 4.] datatype : float64 Program : Convert Celsius to Farenheit In [23]: import numpy as np c_array = np.array([21.3,54.1,36.2,45.6]) print("Celsius values : ", c_array) print() 7
  • 8.
    f_array = c_array*9/5 + 32 print("Farenheit values :", f_array) Celsius values : [ 21.3 54.1 36.2 45.6] Farenheit values : [ 70.34 129.38 97.16 114.08] 1.2.2 arange(x) • Creating ndarray object In [24]: import numpy as np arr = np.arange(20) print('Array : ',arr) Array : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] 1.2.3 Creating 2D arrays In [25]: import numpy as np my_array = np.array([[11,23],[33,44]]) print('2D array') print(my_array) 2D array [[11 23] [33 44]] Program : Matrix Operations In [26]: import numpy as np a = np.array([[1,1],[1,1]]) b = np.array([[1,1],[1,1]]) c = np.matrix('1,1;1,1') d = np.matrix('1,1,1;1,1,1') print("Matrix Addition") print(a+b) print("Matrix Multiplication of equal order") print(a*b) print("Matrix Multiplication of unequal order") print(c*d) Matrix Addition [[2 2] [2 2]] 8
  • 9.
    Matrix Multiplication ofequal order [[1 1] [1 1]] Matrix Multiplication of unequal order [[2 2 2] [2 2 2]] 1.2.4 matrix() in NumPy • Creating a Matrix In [27]: import numpy as np my_matrix = np.matrix('1,2,3;4,5,6;7,8,9') print("Matrix") print(my_matrix) Matrix [[1 2 3] [4 5 6] [7 8 9]] 1.2.5 Basic Slicing Array Slicing • Using slice object In [28]: import numpy as np arr = np.arange(20) print("Original array :", arr) print() #Creating slice object using slice(start,stop,step)in NumPy slice_arr = slice(1,20,2) #Slice object is passed to the array to create a new array s_arr = arr[slice_arr] print('Sliced array :',s_arr) print() print('Origianl array : ', arr) Original array : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] Sliced array : [ 1 3 5 7 9 11 13 15 17 19] 9
  • 10.
    Origianl array :[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] • Using colon separators In [29]: import numpy as np arr = np.arange(20) print("Original array :", arr) print() #Slice object is passed to the array to create a new array s_arr = arr[1:20:2] print('Sliced array :',s_arr) print() print('Origianl array : ', arr) print() print('Reversing Array using slicing :', arr[::-1]) Original array : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] Sliced array : [ 1 3 5 7 9 11 13 15 17 19] Origianl array : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] Reversing Array using slicing : [19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0] Matrix Slicing • using colon separators In [30]: import numpy as np x = np.matrix('11,12,13,14;21,22,23,24;31,32,33,34;41,42,43,44') print('Matrix') print(x) print() print(x[1:3]) print() Matrix [[11 12 13 14] [21 22 23 24] [31 32 33 34] [41 42 43 44]] 10
  • 11.
    [[21 22 2324] [31 32 33 34]] • using ellipsis(...) – for making tuple selection of the same length as array dimension In [31]: import numpy as np x = np.matrix('11,12,13,14;21,22,23,24;31,32,33,34;41,42,43,44') print(' Original Matrix') print(x) print() #Column selection print('Column 1 selection :') print(x[...,1]) print() #Column slicing print('Slicing from Column 1 onwards :') print(x[...,1:]) print() #Row Selection print('Row 1 selection :') print(x[1,...]) Original Matrix [[11 12 13 14] [21 22 23 24] [31 32 33 34] [41 42 43 44]] Column 1 selection : [[12] [22] [32] [42]] Slicing from Column 1 onwards : [[12 13 14] [22 23 24] [32 33 34] [42 43 44]] Row 1 selection : [[21 22 23 24]] 11
  • 12.
    1.2.6 Advanced indexing •Two kinds 1. Integer Indexing – based on N Dimensional index – any arbitrary element in an array can be selected 2. Boolean Indexing – used when the result is meant to be the result of boolean operations Integer Indexing In [32]: import numpy as np a = np.matrix('1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16') print('Original Matrix') print(a) print() # row contains row indices and col contains column indices for elements in the corners row = np.array([[0,0],[3,3]]) col = np.array([[0,3],[0,3]]) # row and col indices are combined to form a new ndarray object b = a[row,col] print(b) print() # row contains row indices and col contains column indices for elements in the middle row1 = np.array([[1,1],[2,2]]) col1 = np.array([[1,2],[1,2]]) # row and col indices are combined to form a new ndarray object b1 = a[row1,col1] print(b1) print() # row contains row indices and col contains column indices for elements in the middle e row2 = np.array([[1,1],[2,2]]) col2 = np.array([[0,3],[0,3]]) # row and col indices are combined to form a new ndarray object b2 = a[row2,col2] print(b2) Original Matrix [[ 1 2 3 4] 12
  • 13.
    [ 5 67 8] [ 9 10 11 12] [13 14 15 16]] [[ 1 4] [13 16]] [[ 6 7] [10 11]] [[ 5 8] [ 9 12]] Combining Basic and Advanced Indexing In [33]: import numpy as np a = np.matrix('1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16') print('Original Matrix') print(a) print() s1 = a[1:,:3] print(s1) print() #Advanced Slicing for column ad = a[1:3,[1,2]] print(ad) Original Matrix [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] [[ 5 6 7] [ 9 10 11] [13 14 15]] [[ 6 7] [10 11]] Boolean Indexing In [34]: import numpy as np a = np.matrix('1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16') 13
  • 14.
    print('Original Matrix') print(a) print() #Printing elementsless than 15 s = arr[arr<15] print('Array with <15 items :',s) Original Matrix [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] Array with <15 items : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14] In [35]: import numpy as np a = np.array([20,20+1j,56,12-1j]) print(a) print(a.dtype) #To extract complex elements in the existing array c = a[np.iscomplex(a)] print('Complex array : ',c) [ 20.+0.j 20.+1.j 56.+0.j 12.-1.j] complex128 Complex array : [ 20.+1.j 12.-1.j] 1.2.7 Array Manipulations • NumPy contains different routines and functions for processing multi-dimensional arrays • Some of the commonly used functions are: 1. reshape(newshape) & resize(array,newshape) 2. flatten(order) & ravel(order) 3. transpose(array) & T 4. concatenate((arr1,arr2),axis) 5. split([indices],axis) reshape(newshape) and resize(newshape) • where newshape should be compatibe with original shape In [36]: import numpy as np a = np.arange(20) 14
  • 15.
    print('Original Array', a) print() a1= a.reshape(4,5) print('Reshaped Array (4*5)') print(a1) print() a2 = np.resize(a,(2,10)) print('Reshaped Array (2*10)') print(a2) Original Array [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] Reshaped Array (4*5) [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] Reshaped Array (2*10) [[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19]] flatten(order) and ravel(order) • where order - row major (’C’), col major (’F’) In [37]: a2 = a1.flatten(order = 'F') print('Flattened Matrix in col major order :') print(a2) print() a3 = a1.ravel(order = 'C') print('Flattened Matrix in row major order :') print(a3) Flattened Matrix in col major order : [ 0 5 10 15 1 6 11 16 2 7 12 17 3 8 13 18 4 9 14 19] Flattened Matrix in row major order : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] transpose() In [38]: print('Original Matrix') print(a1) 15
  • 16.
    print() t = a1.transpose() print('TransposeMatrix') print(t) print() t1 = t.T print('Transpose of transposed matrix') print(t1) print() Original Matrix [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] Transpose Matrix [[ 0 5 10 15] [ 1 6 11 16] [ 2 7 12 17] [ 3 8 13 18] [ 4 9 14 19]] Transpose of transposed matrix [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] concatenate((arr1, arr2, ... ), axis) • concatenates arrays of same shape along a specified axis • arr1, arr2, ... : sequence of arrays of same type • axis : axis along which arrays must be joined – 0 (x-axis ) / 1 (y-axis) In [39]: a1 = np.array([[11,12,13],[14,15,16],[17,18,19]]) print('Original Matrix 1') print(a1) print() a2=a1.T print('Original Matrix 2') print(a2) 16
  • 17.
    print() c1 = np.concatenate((a1,a2)) print('ConcatenatedMatrix at axis = 0 (x-axis)') print(c1) print() c2 = np.concatenate((a1,a2),axis = 1) print('Concatenated Matrix at axis = 1 (y-axis)') print(c2) print() Original Matrix 1 [[11 12 13] [14 15 16] [17 18 19]] Original Matrix 2 [[11 14 17] [12 15 18] [13 16 19]] Concatenated Matrix at axis = 0 (x-axis) [[11 12 13] [14 15 16] [17 18 19] [11 14 17] [12 15 18] [13 16 19]] Concatenated Matrix at axis = 1 (y-axis) [[11 12 13 11 14 17] [14 15 16 12 15 18] [17 18 19 13 16 19]] split(arr, [indices], axis) • breaks the array into subarrays along a specified axis • arr : array to be divided • indices : integer specifying the number of equal sized sub-arrays • axis : along which the array is split – 0 (x-axis) / 1 (y-axis) In [40]: a1 = np.array([[11,12,13],[14,15,16],[17,18,19]]) print('Original Matrix 1') print(a1) 17
  • 18.
    print() #split at axis= 0 (x-axis) x,y,z = np.split(a1,[1,2]) print('split at axis = 0 (x-axis)') print('Subarray 1 :', x) print() print('Subarray 2 :', y) print() print('Subarray 3 :', z) #split at axis = 1 (y-axis) x,y,z = np.split(a1,[1,2], axis =1) print('split at axis = 1 (y-axis)') print('Subarray 1 :') print(x) print() print('Subarray 2 :') print(y) print() print('Subarray 3 :') print(z) Original Matrix 1 [[11 12 13] [14 15 16] [17 18 19]] split at axis = 0 (x-axis) Subarray 1 : [[11 12 13]] Subarray 2 : [[14 15 16]] Subarray 3 : [[17 18 19]] split at axis = 1 (y-axis) Subarray 1 : [[11] [14] [17]] Subarray 2 : [[12] [15] [18]] Subarray 3 : [[13] [16] 18
  • 19.
    [19]] insert(arr, pos, values,axis) • arr : array • pos : index before which insertion is to be made • values : array of values to be inserted along axis • axis : 0 (x-axis) / 1 (y-axis) In [41]: arr1 = np.array([[11,12,13],[21,22,23]]) list1 = [31,32,33] arr2 = np.insert(arr1,1,list1,0) print(arr2) print() list2 = [41,42] arr3 = np.insert(arr1,2,list2,1) print(arr3) [[11 12 13] [31 32 33] [21 22 23]] [[11 12 41 13] [21 22 42 23]] append(arr,values,axis) • arr : array • values: list of values to be appended • axis : 0 (x-axis)/ 1 (y-axis) along which append operation is to be performed In [42]: arr1 = np.arange(6) print(arr1.ndim) print(arr1) list1 = [int(x) for x in input("Enter the 3 numbers separated by comma :").strip().spli print(list1) arr2 = np.append(arr1,list1,0) print(arr2) 1 [0 1 2 3 4 5] Enter the 3 numbers separated by comma :9,6,7 [9, 6, 7] [0 1 2 3 4 5 9 6 7] 19
  • 20.
    delete(arr, obj, axis) •arr : array • obj : object to be deleted • axis : 0 (x-axis) / 1 (y-axis) along which deletion is to be performed In [43]: arr1 = np.arange(25).reshape(5,5) arr2 = np.delete(arr1,1,1) arr3 = np.delete(arr1,2,0) print("arr1 : ") print(arr1) print("arr2 : ") print(arr2) print("arr3 : ") print(arr3) arr1 : [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]] arr2 : [[ 0 2 3 4] [ 5 7 8 9] [10 12 13 14] [15 17 18 19] [20 22 23 24]] arr3 : [[ 0 1 2 3 4] [ 5 6 7 8 9] [15 16 17 18 19] [20 21 22 23 24]] 20