Creating 1D ndarray
The following example creates an 1D ndarray using a list.
import numpy as np
a = np.array([1,2,3,4])
print(a)
print('Dimension:',a.shape)# dimension of the array- (4 rows for 1 D array)
print('Datatype:',a.dtype)
print('Size of each element:', a.itemsize, 'bytes')
OUTPUT:
[1 2 3 4]
Dimension: (4,)
Datatype: int64
Size of each element: 8 bytes
We can create an array with smaller size by mentioning the dtype specifically to int16 or int8
import numpy as np
a = np.array([1,2,3,4], dtype='int8')
print(a.dtype)
print('Size of each element:', a.itemsize, 'byte')
OUTPUT:
int8
Size of each element: 1 byte
- fromiter() function can be create a numpy array using any iterable (that can be traversed through) object like string, list or a dictionary
- The following examples illustrate the use of fromiter() method
#This example creates an array of unicode charactersrs from a string
#The dtype needs to be exclusively given (Unicode 2 bytes)
import numpy as np
st ="NUMPY"
arr = np.fromiter(st, dtype='U2')
print(arr)
#This example creates an array of integers from a loop
itr = (x*x for x in range(1,8))
arr = np.fromiter(itr, dtype='int8')
print(arr)
#This example will create a dictionary of keys of a dictionary
dic = {'A':10, 'B':20, 'C':20}
arr = np.fromiter(dic, dtype='U2')
print(arr)
#The last example will create an arry selecting only first 5 charecters of the string
#For this we need to set the count attribute to a desired value
st = "PYTHONLANG"
arr = np.fromiter(st, dtype='U2', count=5)
print(arr)
OUTPUT :
['N' 'U' 'M' 'P' 'Y']
[ 1 4 9 16 25 36 49]
['A' 'B' 'C']
['P' 'Y' 'T' 'H' 'O']
We use 0 based indexing for accessing the elements of an ndarray
import numpy as np
a = np.array([1,2,3,4], dtype='int8')
print('The first element:',a[0])
print('The last element:',a[3])
OUTPUT:
The first element: 1
The last element: 4
We can pass a 2D list in the array() function of numpy to create a 2D ndarray as shown below.
import numpy as np
b = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(b)
print('The shape is:',b.shape)
OUTPUT:
[[1 2 3]
[4 5 6]
[7 8 9]]
The shape is: (3, 3)
The following examples illustrates the use of 0 based indexing on 2D array
import numpy as np
b = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(b)
print('first row:',b[0])
print('First row 1st element:',b[0][0])
print('Third row 3rd element:',b[2][2])
print('Second row 1st element:',b[1,0])
OUTPUT:
[[1 2 3]
[4 5 6]
[7 8 9]]
first row: [1 2 3]
First row 1st element: 1
Third row 3rd element: 9
Second row 1st element: 4
Creating matrix of 0s using the zeros() function.
Observe that the dtype of the resulting matrix of zeros is float64
import numpy as np
b = np.zeros((3,3)) # Creates a 3x3 matrix with zeros
print(b)
print(b.dtype)
OUTPUT:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
float64
import numpy as np
b = np.ones((3,3)) # Creates a 3x3 matrix with ones
print(b)
print(b.dtype)
OUTPUT:
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
float64
This function accepts two parameters - size as tuple and the data value as a number
import numpy as np
b = np.full((2,2), 8) # Creates a 2x2 constant matrix with 8
print(b)
OUTPUT:
[[8 8]
[8 8]]
This method accepts one parameter as the size of the identity matrix.
import numpy as np
b = np.eye(3) # Creates an identity matrix
print(b)
OUTPUT:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
- Random numbers can be generated using the random library of numpy.
- The following statement creates a a 2x2 matrix using random.random() funcion
import numpy as np
b = np.random.random((2,2)) # Creates an random number matrix
print(b)
OUTPUT:
[[0.53352925 0.48243526]
[0.51794348 0.46761645]]
#Using arange function to create a numpy array
import numpy as np
# creates an array of integers from 0 to 9
b = np.arange(10)
print(b)
# creates an array of floats from 1 to 10
a = np.arange(1,11, dtype=float)
print(a)
# Creates an array with interval of 0.1
c = np.arange(2,3, 0.1)
print(c)
OUTPUT:
[0 1 2 3 4 5 6 7 8 9]
[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
[2. 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9]
- Slicing of numpy arrays creates sub-arrays from and existing array
- Any modification done in the subarray is reflected back in the main array
#Slicing of numpy arrays
#Resultant array will always be a sub-array of the original array
import numpy as np
a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
b = a[0:2] # slice consists of only first two row (excludes row three)
print('b:',b)
c = a[1:2] # Slice consists of only second row
print('c:',c)
d = a[0:1,0:4] # Slice consists of entire first row (first row all columns)
print('d:',d)
e = a[0:1,0:2] # Slice consists of first row and first two columns
print('e:',e)
f = a[0:1,2:4] # Slice consists of first row and columns three and four
print('f:',f)
OUTPUT:
b: [[1 2 3 4]
[5 6 7 8]]
c: [[5 6 7 8]]
d: [[1 2 3 4]]
e: [[1 2]]
f: [[3 4]]
#Slicing of numpy arrays
import numpy as np
a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
b = a[1:2,0:4] # Slice consists of second row all columns
print('b:',b)
c = a[1:2,1:2] # Slice consists of second row second column
print('c:',c)
d = a[:2,0:2] # Slice consists of two rows first[1,2] and second[5,6]
print('d:',d)
e = a[:2,1:3] # Slice consists of two rows first[2,3] and second[6,7]
print('e:',e)
f = a[1:3,2:4] # Slice consists of two rows first[7,8] and second[11,12]
print('f:',f)
OUTPUT:
b: [[5 6 7 8]]
c: [[6]]
d: [[1 2]
[5 6]]
e: [[2 3]
[6 7]]
f: [[ 7 8]
[11 12]]
#Indexing will create a new arbitry array from the original array
import numpy as np
a = np.array([[1,2], [3, 4], [5, 6]])
print(a.shape)
b = a[[0,1,2],[0,1,0]] # The resultant array will have shape (3,)
print(b)
print(b.shape)
OUTPUT:
(3, 2)
[1 4 5]
(3,)
#Changing the values in an array resulting from slice
import numpy as np
a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
b = a[0:2,1:3] #Sliced array
print(b)
b[0,0]=20 # Changing the value in the slice
print(b)
print(a) # The change is getting reflected in the original array
OUTPUT:
[[2 3]
[6 7]]
[[20 3]
[ 6 7]]
[[ 1 20 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
#Joining two numpy arrays
import numpy as np
a = np.array([[1,2],[2,4]])
b = np.array([[7,8]])
#Joing as row
c = np.concatenate((a,b), axis=0)
print(c)
#Joinging as column
d = np.concatenate((a,b.T), axis=1)
print(d)
OUTPUT:
[[1 2]
[2 4]
[7 8]]
[[1 2 7]
[2 4 8]]
Unlike lists the aritmatic operations on numpy arrays are vector operations
Addition, subtraction, simple multipliction, matrix multiplication, division, square root
Addition of two arrays: np.add(a,b) or a+b
Subtraction of two arrays: np.subtract(a,b) or a-b
Simple multiplication: np.multiply(a,b) or a*b
Division of two arrays: np.divide(a,b) or a/b
Matrix multiplication: np.dot(a,b) or a.dot(b)
#Numpy arithmatic operations
import numpy as np
a = np.array([[1,2],[3,4]], dtype=np.int32)
b = np.array([[5,6],[7,8]], dtype=np.int32)
print(a+b)
print(np.add(a,b))
print(a-b)
print(np.subtract(a,b))
print(a*b) # Multiplies corresponding elements
print(np.multiply(a,b))
print(a/b)
print(np.divide(a,b))
print(np.sqrt(a))
# Actual Matrix multiplication
print(a.dot(b))
print(np.dot(a,b))
OUTPUT:
[[ 6 8]
[10 12]]
[[ 6 8]
[10 12]]
[[-4 -4]
[-4 -4]]
[[-4 -4]
[-4 -4]]
[[ 5 12]
[21 32]]
[[ 5 12]
[21 32]]
[[0.2 0.33333333]
[0.42857143 0.5 ]]
[[0.2 0.33333333]
[0.42857143 0.5 ]]
[[1. 1.41421356]
[1.73205081 2. ]]
[[19 22]
[43 50]]
[[19 22]
[43 50]]
- for axis=0 there will be row sum
- for axis=1 there will be column sum
#numpy sum() function
a = np.array([[1,2],[3,4]], dtype=np.int32)
print(np.sum(a, axis=0))
print(np.sum(a, axis=1))
[4 6]
[3 7]