Array Notes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

T1: Introduction

1. Can store only one type of data


2. Can increase or decrease their size dynamically.
3. For help: >>> help() help> array

T2: Advantages of arrays


1. Faster compare to the list.

T3: Creating an Array


1. Syntax:
• arrayname = array(type_code, [elements])
2. Type codes:
• Refere Table 7.1
3. Examples:
• a = array(‘i’, [2, 4, 6, 8])
• b = array(‘d’, [1.5, 4.5])

T4: Importing the Array Module


1. import array
a = array.array(‘i’, [1, 2, 3, 4])
2. import array as arr
b = arr.array(‘i’, [1, 2, 3, 4])
3. from array import *
a = array(‘i’, [1, 2, 3, 4])
4. Copying the array items
• a = array(‘i’, [1, 2, 3, 4])
• b = array(a.typecode, (i for i in a))
• c = array(a.typecode, (i * 5 for i in a))

T5: Indexing and slicing on Arrays


1. Printing array items using index
• n = len(arr)
• for i in range(n):
– print(arr[i])
2. Slicing
1. Syntax:
• arrayname[start: stop: stride]
2. Examples:
1. y = a[1: 4]

1
2. y= a[0: ]
3. y= x[:4]
4. y= x[-4:]
5. y= x[-4, -1]
6. y= x[0: 7: 2]
7. x[1: 3] = array(‘i’, [10, 20])

T6: Processing the arrays


1. Refer Table-7.2
2. arrays class of arrays module.
3. objectname.method()

T7: Types of Arrays


1. 1D array
• a = array(‘i’, [10, 20, 30, 40, 50])
2. 2D array
• a = array([[10, 20]
• [30, 40]
• [50, 60]])

T8: Working with Arrays using numpy


1. Ways of importing
• import numpy
• import numpy as nm
• from numpy import *
2. Creating arrays using several ways
• array()
• linspace()
• logspace()
• arange()
• zeros() and ones()

T9: Creating Arrays using array()


1. a = array([10, 20, 30, 40, 50], int)
2. b = array([1.1, 2.2, 3.3, 4.4, 5.5], float)
3. c = array([10, 20, 3.0, 40])
• c is an float type array, no need to specify the type.
• If one item is float, then python converts all to float
4. d = array([‘a’, ‘b’, ‘c’, ‘d’])

2
• No need to specify the type
• Default: char
5. • e = array([‘Bengaluru’, ‘Delhi’, ‘Bombay’], dtype = str)
• e = array([‘Bengaluru’, ‘Delhi’, ‘Bombay’])
– dtype can be skipped
6. Array copy
• a = ([1, 2, 3, 4, 5])
• b = (array(a))
• c=a

T10: Creating Arrays using linspace()


1. Use: To create an array with evenly spaced points between a starting point
and ending point.
2. Syntax: linspace(start, stop, n)
3. Example:
• a = linspace(0, 10, 5)

T11: Creating Arrays using logspace()


1. Use: Produces evenly spaced points on logarithmically spaced scale.
2. Syntax: logspace(start, stop, n)
3. Example:
• a = logspace(1, 4, 5)

T12: Creating Arrays using arange()


1. Same as range()
2. Syntax: arange(start, stop, stepsize)
3. Defaults:
• stepsize = 1
• start = 0
4. Example:
1. arange(10)
2. arange(5, 10)
3. arange(1, 10, 3)
4. arange(10, 1, -1)
5. arange(0, 10, 1.5)
6. arange(2, 11, 2)

3
T13: Creating Arrays using zeros() and ones()
1. Uses:
• zeros(): To create an array with all zeroes
• ones(): To create an array with all ones
2. Syntax:
• zeros(n, datatype)
• ones(n, datatype)
3. Default:
• datatype: float
4. Example:
1. zeros(5)
2. zeros(10, int)
3. zeros(5, float)
4. ones(5, int)
5. ones(5)

T14: Mathematical Operations on Arrays


1. Use math module to perform various mathematical operations on array.
2. Example-1: To add 5 to each item of an array
• a = array([10, 20, 30, 40, 50])
• b=a+5
3. Example-2: To subtract two arrays with equal number of items
• a = array([1, 2])
• b = array([3, 4])
• c=b-a
4. Advantages of vectorized operations
1. Faster
2. synatctically clearer
3. Provides compact code
5. Refer Table: 7.4
6. Example-3: To apply sin on each item of an array
• a = array([10, 20, 30])
• b = sin(a)

T15: Comparing Arrays


1. Comparison operators: > >= < <= == !=
2. Compares the corresponding items of the arrays and return the boolean
values

4
3. Example:
• a = array([1, 2, 3, 4])
• b = array([0, 2, 3, 1])
• c = a == b
• c=a>b
• c=a<b
4. any() and all()
• any(): Returns True, if any one of the item is True
• all(): Returns True, if all the items in the array is True
5. Logical operators on arrays: a = array([0, 10, 3])
• logical_and(a > 0, a < 4)
– Returns [False False True]
• logical_or(a > 4, a < 0)
– Returns [True True False]
• logical_not(a)
– Returns [True Flase False]
6. where()
• Use: To create new array based on whether a given condition is True
or False
• Synatx:
array = where(condition, expression1, expression2)
• Example:
a = array([10, 21, 30, 41, 50])
b = where(a % 2, a, 0)
7. nonzero()
• Use: To know the position of the items which are non zero
• Example:
a = array([1, 2, 0, -1, 0])
b = nonzero(a)

T16: Aliasing the Array


1. a = array([10, 20, 30])
b=a
2. b is another tag name for a

T17: Viewing and copying Arrays


1. view(): Also called ‘Shallow copying’

5
1. Copies the contents of array a to b
2. Any modifications done in b will also be reflected in a
3. Usage: b = a.view()
2. copy(): Also called ‘Deep Copying’
1. Copies the contents of array a to b
2. Any modifications done in b will not be reflected in a
3. Usage: b = a.copy()

T18: Slicing ‘n’ Indexing in numpy Arrays


1. Same as normal slicing
2. Syntax: arrayname[start: stop: stepsize]
3. Defaults:
• start: 0
• stepsize: 1
4. Examples: If a = [10, 11, 12, 13, 14, 15]
1. a[1: 6: 2]
2. a[-1: -4: -1]
3. a[::] -> Retrieves all items of an array
4. a[-2: 2: -1]
5. a[: -2: ]

T19: Dimensions of Arrays


1. 1D Array: a = array([1, 2, 3, 4, 5])
b = array([ 1,
2,
3,
4,
5])

2. 2D Array: a = array([ [1, 2] [3, 4]])


3. 3D Array: a = array([ [ ], [ ] [ ], [ ] ])

T20: Attributes of an Array


1. numpy’s array class is called ndarray
2. Variables | Methods
1. ndim | 1. reshape()
2. shape | 2. flatten()
3. size |

6
4. itemsize |
5. dtype |
6. nbytes |
3. The ndim attribute
1. Gives number of dimensions or axes of an array
2. Usage: arrayname.ndim
4. The shape attribute
1. Gives the shape of the array
2. Example:
• For 1D, shape gives number of items in row
• For 2D, shape gives number of rows ‘n’ cols
3. Usage: arrayname.shape
4. We can change the shape of an array
a.shape = (3, 2) #Changes to 3 Rows ‘n’ 2 Cols
5. The size attribute
1. Gives total number of items in an array
2. Usage: arrayname.size
6. The itemsize attribute
1. Gives the size of item in terms of bytes
2. Usage: arrayname.itemsize
7. The dtype attribute
1. Gives the data type of an array
2. Usage: arrayname.dtype
8. The nbytes attribute
1. Gives total number of bytes occupied by the array in the memory
2. Usage: arrayname.nbyes
3. Total Memory = SIZE * sizeof(item)
9. The reshape() method
1. Useful: To change the shape of the array
2. Example:
• a = arange(10)
• a = a.reshape(2, 5)
– Change the shape to 2 rows n 5 cols
10. The flatten() method
1. Useful: To return the copy the array collapsed to 1D array

7
T21: Working with Multi-Dimensional array
1. Ways creating multi-dimensional arrays
1. array()
2. ones() and zeroes()
3. eye()
4. reshape()
2. The array()
1. a = array([[1, 2], [3, 4]])
2. The memory allocation will be contiguous
3. The ones() and zeros()
1. Syntax: ones((r, c), dtype)
2. Example: ones((3, 4), float)
3. |||ly for zeros()
4. The eye()
1. Creates 2D array ‘n’ fills diagonal elements with ’1’s
2. Syntax: eye(n, dtype = datatype)
3. Default: float
4. Example: a = eye(3)
5. The reshape()
1. Used: To convert 1D into nD arrays
2. Syntax: reshape(arrayname, (n, r, c))
3. Example-1:
a = array([1, 2, 3, 4, 5, 6])
b = reshape(a, (2, 3))
4. Example-2: To convert 1D into 3D array or 2 2D array of size 3x2
a = arange(12)
b = reshape(a, (2, 3, 2))

T22: Indexing in Multi-dimensional Arrays


1. • a[0][0]
• b[1][3]
2. • for i in range(len(a)) #Gives number of rows
– print(a[i])
3. for i in range(len(a))
for j in range(len(a[i]))
print(a[i][j])
4. #For 3D array
• for i in range(len(a)) #Gives number of 2D arrays
– for j in range(len(a[i])) #Gives number of 1D arrays
∗ for k in range(len[i][j]) #Gives the items
· print(a[i][j][k])

8
T23: Slicing in Multi-dimensional array
1. Syntax: arrayname[start, stop, stepsize] - arrayname[row : col: stepsize] -
arrayname[start: stop, start: stop, stepsize] #This is refined syntax
2. Default:
• start: 0
• stop: n
• stepsize: 1
3. Examples:
1. a[: , :]
• a[::]
• a[:]
• Display’s the entire 2D arrays
2. a[0, :] -> Displays 0th row items
3. a[:, 0] -> Displays 0th col items
4. a[0:1, 0:1] -> Displays 0th row, 1st col item
• a[1:2, 1:2] -> Displays 1st row, 2nd col item
5. a[0:2, 0:3]
• 0th row to 1st row
• 0th col to 2nd col
6. a[2:4, 3: ]
• 2nd to 3rd row
• 3rd col to end

T24: Matrices in numpy


1. Creating the matrix using numpy module
• syntax: matrix-name = matrix(2D array or string)
2. Example-1:
• a = [[1, 2], [3, 4]]
• b = matrix(a)
3. Example-2:
• a = matrix([[], []])
4. Example-3:
• str = ‘1 2; 3 4; 5 6’
• b = matrix(str)
5. Example-4:
• a = matrix(“1 2; 3 4; 5 6”)

9
T25: Getting diagonal elements of a matrix
1. To retrieve a diagonal items from a matrix use diagonal()
2. Syntax: diagonal(matrix)
3. Example:
• a = diagonal(matrix)

T26: Finding maximum and minimum items


1. Methods:
• max()
• min()
2. Usage:
• a.max()
• a.min()

T27: Finding the sum and average of items


1. Methods:
• sum()
• mean()
2. Usage:
• a.sum()
• a.mean()

T28: Products of items


1. Method: prod()
2. Example:
• m = matrix(arange(12).reshape(3, 4))
• a = m.prod(0) #Finds product of items col-wise
• a = m.prod(1) #Finds product of items row-wise

T29: Sorting the matrix


1. Function: sort()
2. Syntax: sort(matrixname, axis)
3. If axis = 1, sorts elements in each row in ascending order
• If axis = 0, sorts elements in each col in ascending order
• Default is 1

10
T30: Transpose of a Matrix
1. Methods:
• transpose()
• getT()
2. t = m.transpose() - t = m.getT()

T31: Matrix Addition and Multiplication


1. If a, b are two matrices of equal order, then
• c=a+b
• c=a-b
• c=a*b
• c=a/b
• All are valid operations

T32: Random numbers


1. numpy has sub module random which has rand() to create random numbers
2. Example:
• a = random.rand()
• b = random.rand(5) #Creates 1D array with 5 items
• c = random.rand(2, 3) #Creates 2D array with 6 items

11

You might also like