Array creation using array module
Example
Python
import array
a = array.array('i',[10,20,30]) # i represents int type array
print(f"Type of a ⇒ {type(a)}") # array.array
print(f"a value ⇒ {a}")
print("Elements one by one")
for x in range(len(a)):
print(a[x])
Output
PowerShell
Type of a ⇒ <class 'array.array'>
a value ⇒ array('i', [10, 20, 30])
Elements one by one
10
20
30
Note
- Array module is not recommended to use because much library support is not available.
Array creation using numpy
- The array object in Numpy is called ndarray.
- We can create a Numpy ndarray object by using the following function:
- array()
- arange()
- linspace()
- zeros()
- ones()
- full()
- eye()
- identity()
- diag()
- empty()
- – randint()
- – rand()
- – uniform()
- – randn()
- – normal()
- – shuffle()
- Using np.random module:
- randint()
- rand()
- uniform()
- randn()
- normal()
- shuffle()
Note
- np.random module is developed based on array. So performance of this module is more when compared with normal python random module.
array()
- array() function is used for creating 1-D array using list or tuple.
Example
Python
import numpy as np
my_list = [10,20,30]
print(f'Type of my_list ⇒ {type(my_list)}')
my_array = np.array(my_list )
print(f'Type of my_array ⇒ {type(my_array)}')
print(f"my_array ⇒ {my_array}")
Output
PowerShell
Type of my_list ⇒ <class 'list'>
Type of my_array ⇒ <class 'numpy.ndarray'>
my_array ⇒ [10 20 30]
Note
- To know properties of ndarray:
- np.ndim ⇒ To know the dimension of the ndarray.
- np.dtype ⇒ To know the data type of the elements in the ndarray.
- np.size ⇒ To know the total number of elements in the array.
- np.shape ⇒ Returns the shape of an array in tuple form.
Example
Python
import numpy as np
my_list = [10,20,30]
print(f'Type of my_list ⇒ {type(my_list)}')
my_array = np.array(my_list )
print(f'Type of my_array ⇒ {type(my_array)}')
print(f"my_array ⇒ {my_array}")
print(f'The dimensions of the array a ⇒ {my_array.ndim}')
print(f'The data type of elements of array a ⇒ {my_array.dtype}')
print(f'The size of the array a ⇒ {my_array.size}')
print(f'The shape of the array a ⇒ {my_array.shape}')
Output
PowerShell
Type of my_list ⇒ <class 'list'>
Type of my_array ⇒ <class 'numpy.ndarray'>
my_array ⇒ [10 20 30]
The dimensions of the array a ⇒ 1
The data type of elements of array a ⇒ int64
The size of the array a ⇒ 3
The shape of the array a ⇒ (3,)
- array() function is also used for creating 2-d array using nested list.
Example
Python
import numpy as np
my_list = [[10,20,30],[40,50,60],[70,80,90]]
my_array = np.array(my_list)
print(f'Type of my_array ⇒ {type(my_array)}')
print(f'my_array ⇒ \n {my_array}')
Output
PowerShell
Type of my_array ⇒ <class 'numpy.ndarray'>
my_array ⇒
[[10 20 30]
[40 50 60]
[70 80 90]]
Note
- Array contains only homogenous elements.
- If list contains heterogenous elements, and while creating the array upcasting will be performed.
Example
Python
# list contains heterogenous elements
l = [10,20,30.5]
a = np.array(l) # upcasting to float
print(f'a :: {a}')
print(f'data type of elements of a ⇒ {a.dtype}')
Output
PowerShell
a :: [10. 20. 30.5]
data type of elements of a ⇒ float64
Creating arrays with particular datatype
- we have to use dtype argument while creating the arrray.
Example
Python
# int type
a = np.array([10,20,30.5],dtype=int)
print(a)
Output
PowerShell
[10 20 30]
Example
Python
# float type
a = np.array([10,20,30.5],dtype=float)
print(a)
Output
PowerShell
[10. 20. 30.5]
Example
Python
# bool type ==> any number is True and zero is False. Any string is True and empty
string is False
a = np.array([10,20,30.5],dtype=bool)
print(a)
Output
PowerShell
[ True True True]
Example
Python
# complex type
a = np.array([10,20,30.5,0],dtype=complex)
print(a)
Output
PowerShell
[10. +0.j 20. +0.j 30.5+0.j 0. +0.j]
Example
Python
# str type
a = np.array([10,20,30.5],dtype=str)
print(a)
Output
PowerShell
['10' '20' '30.5']
creating object type array
- Object is the parent of all int, float, bool, complex and str.
- Here the elements are looks like heterogeneous. But the datatype of elements is ‘object’.
Example
Python
a = np.array([10,'krishna',10.5,True,10+20j],dtype=object)
print(a)
# data type
print(f"Data type of elements of array a ==> {a.dtype}")
Output
PowerShell
[10 'krishna' 10.5 True (10+20j)]
Data type of elements of array a ⇒ object
arange()
- we can create only 1-D arrays with arange() function.
Python
import numpy as np
help(np.arange)
Output
PowerShell
Help on built-in function arange in module numpy:
arange(...)
arange([start,] stop[, step,], dtype=None, *, like=None)
Return evenly spaced values within a given interval.
Values are generated within the half-open interval ``[start, stop)``
(in other words, the interval including `start` but excluding `stop`).
For integer arguments the function is equivalent to the Python built-in
`range` function, but returns an ndarray rather than a list.
When using a non-integer step, such as 0.1, the results will often not
be consistent. It is better to use `numpy.linspace` for these cases.
Python
- range(n) ⇒ n values from 0 to n-1.
- range(4) ⇒ 0,1,2,3.
- range(m,n)⇒ from m to n-1.
- range(2,7)⇒ 2,3,4,5,6.
- range(begin,end,step).
- range(1,11,1) ⇒ 1,2,3,4,5,6,7,8,9,10.
- range(1,11,2) ⇒ 1,3,5,7,9.
- range(1,11,3) ⇒ 1,4,7,10.
Example
Python
# only stop value ⇒ 0 to stop-1
import numpy as np
a = np.arange(10)
print(f'a ⇒ {a}')
print(f'The dimensions of the array a ⇒ {a.ndim}')
print(f'The data type of elements of array a ⇒ {a.dtype}')
print(f'The size of the array a ⇒ {a.size}')
print(f'The shape of the array a ⇒ {a.shape}')
Output
PowerShell
a ⇒ [0 1 2 3 4 5 6 7 8 9]
The dimensions of the array a ⇒ 1
The data type of elements of array a ⇒ int32
The size of the array a ⇒ 10
The shape of the array a ⇒ (10,)
Example
Python
# both start and stop values: start to stop-1
import numpy as np
a = np.arange(1,11)
print(f'a ⇒ {a}')
print(f'The dimensions of the array a ⇒ {a.ndim}')
print(f'The data type of elements of array a ⇒ {a.dtype}')
print(f'The size of the array a ⇒ {a.size}')
print(f'The shape of the array a ⇒ {a.shape}')
Output
PowerShell
a ⇒ [ 1 2 3 4 5 6 7 8 9 10]
The dimensions of the array a ⇒ 1
The data type of elements of array a ⇒ int32
The size of the array a ⇒ 10
The shape of the array a ⇒ (10,)
Example
Python
# start, stop and step values : start to stop-1 with step
import numpy as np
a = np.arange(1,11,2)
print(f'a ⇒ {a}')
print(f'The dimensions of the array a ⇒ {a.ndim}')
print(f'The data type of elements of array a ⇒ {a.dtype}')
print(f'The size of the array a ⇒ {a.size}')
print(f'The shape of the array a ⇒ {a.shape}')
Output
PowerShell
a ⇒ [1 3 5 7 9]
The dimensions of the array a ⇒ 1
The data type of elements of array a ⇒ int32
The size of the array a ⇒ 5
The shape of the array a ⇒ (5,)
Example
Python
# with a particular datatype of the elements
import numpy as np
a = np.arange(1,11,3,dtype=float)
print(f'a ⇒ {a}')
print(f'The dimensions of the array a ⇒ {a.ndim}')
print(f'The data type of elements of array a ⇒ {a.dtype}')
print(f'The size of the array a ⇒ {a.size}')
print(f'The shape of the array a ⇒ {a.shape}')
Output
PowerShell
a ⇒ [ 1. 4. 7. 10.]
The dimensions of the array a ⇒ 1
The data type of elements of array a ⇒ float64
The size of the array a ⇒ 4
The shape of the array a ⇒ (4,)
linspace()
- same as arange() only but in the specified interval, linearly spaced values.
Example
Python
import numpy as np
help(np.linspace)
Output
PowerShell
Help on function linspace in module numpy:
linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None axis=0)
Return evenly spaced numbers over a specified interval.
Returns `num` evenly spaced samples, calculated over the
interval [`start`, `stop`].
linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0).
- Both start and stop are includded because endpoint=True.
- If endpoint=False then stop is excluded.
- retstep denotes the spacing between the points.If true then the value is returned.
- calculation of spacing (stop-start)/(num-1) if endpoint=True.
- calculation of spacing (stop-start)/(num) if endpoint=False.
Example
Python
# 50 evenly spaced values between 0 and 1 are returned including both 0 and1
np.linspace(0,1 )
Output
Example
Python
# 4 evenly spaced valued between 0 and 1 including 0 and 1
np.linspace(0,1,4)
Output
PowerShell
array([0. , 0.33333333, 0.66666667, 1.])
Example
Python
# 4 evenly spaced valued between 0 and 1 including 0 and excluding 1
np.linspace(0,1,4,endpoint=False)
Output
PowerShell
array([0. , 0.25, 0.5 , 0.75])
Example
Python
# 4 evenly spaced valued between 0 and 1 including 0 and excluding 1 and return
spacing
np.linspace(0,1,4,endpoint=False,retstep=True)
Output
PowerShell
(array([0. , 0.25, 0.5 , 0.75]), 0.25)
Example
Python
# 10 values between 1 to 100 including 1 and 100 with equally spaced int values
np.linspace(1,100,10,dtype=int,retstep=True)
Output
PowerShell
(array([ 1, 12, 23, 34, 45, 56, 67, 78, 89, 100]), 11.0)
arange() vs linspace()
- arange() ⇒ Elements will be considered in the given range based on step value.
- linspace() ⇒ The specified number of values will be considered in the given range.
zeros
- array is filled with 0s.
Example
Python
import numpy as np
help(np.zeros)
Output
PowerShell
Help on built-in function zeros in module numpy
zeros(...)
zeros(shape, dtype=float, order='C', *, like=None)
Return a new array of given shape and type, filled with zeros.
Parameters
----------
shape : int or tuple of ints
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
dtype : data-type, optional
The desired data-type for the array, e.g., `numpy.int8`.
`numpy.float64`.
order : {'C', 'F'}, optional, default: 'C'
Whether to store multi-dimensional data in row-major
(C-style) or column-major (Fortran-style) order in
memory.
- 0-D array ⇒ Scalar :: single value.
- 1-D array ⇒ Vector :: Collection of 0-D arrays.
- 2-D array ⇒ Matrix :: Collection of 1-D arrays.
- 3-D array ⇒ collcetion of 2-D arrays.
- (10,) ⇒1-D array contains 10 elements.
- (5,2) ⇒2-D array contains 5 rows and 2 columns.
- (2,3,4) ⇒3-Darray.
- 2 ⇒ number of 2-D arrays.
- 3 ⇒ The number of rows in every 2-D array.
- 4 ⇒ The number of columns in every 2-D array.
- size: 2* 3* 4 = 24.
Example
Python
# zeros(shape, dtype=float, order='C', *, like=None) ⇒ shape always in tuple form
# 1-D array with zeros
np.zeros(4)
Output
PowerShell
array([0., 0., 0., 0.])
Example
Python
# 2-D arrays with zeros
np.zeros((4,3))
Output
PowerShell
array([[0.,0., 0.],
[0.,0., 0.],
[0.,0.,0.],
[0., 0.,0.]])
Example
Python
# 3-D array
np.zeros((2,3,4))
Output
PowerShell
array([[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]],
[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]])
Note: observe the above output.
- outermost there are 3 square brackets are present means it is 3-D array.
- exclude one outermost bracket then it is a 2-D array ==> total 2 2-D arrays present.
- Each 2-D array contains 1-D arrays. Each 2-D contains 3-rows and 4-columns.
Example
Python
# 4-D array ==> collection of 3-D arrays
# (2,2,3,4)
# 2 ==> no. of 3-D arrays
# 2 ==> every 3-D 2 2-D arrays
# 3 ==> Every 2-D array contains 3 rows
# 4 ==> every 2-D array contains 4 columns
np.zeros((2,2,3,4))
Output
PowerShell
array([[[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]],
[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]],
[[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]],
[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]]])
ones()
- exactly same as zeros except array is filled with 1.
Example
Python
import numpy as np
help(np.ones)
Output
PowerShell
Help on function ones in module numpy:
ones(shape, dtype=None, order='C', *, like=None)
Return a new array of given shape and type, filled with ones.
Parameters
----------
shape : int or sequence of ints
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
dtype : data-type, optional
The desired data-type for the array, e.g., `numpy.int8`.
`numpy.float64`.
order : {'C', 'F'}, optional, default: C
Whether to store multi-dimensional data in row-major
(C-style) or column-major (Fortran-style) order in
memory.
Example
PowerShell
# 1-D array
np.ones(10)
Output
PowerShell
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
Example
Python
# 2-D array
np.ones((5,2),dtype=int)
Output
PowerShell
array([[1, 1],
[1, 1],
[1, 1]
[1, 1],
[1, 1]])
Example
Python
# 3-D array
np.ones((2,3,4),dtype=int)
Output
PowerShell
array([[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]],
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]])
full
- Return a new array of given shape and type, filled with fill_value .
Example
Python
import numpy as np
help(np.full)
Output
PowerShell
Help on function full in module numpy:
full(shape, fill_value, dtype=None, order='C', *, like=None)
Return a new array of given shape and type, filled with `fill_value`.
Parameters
----------
shape : int or sequence of ints
Shape of the new array, e.g., ``(2, 3)`` or ``2`
fill_value : scalar or array_like
Fill value.
dtype : data-type, optional
The desired data-type for the array The default, None, means
`np.array(fill_value).dtype`.
order : {'C', 'F'}, optional
Whether to store multidimensional data in C- or Fortran-contiguous
(row- or column-wise) order in memory.
Example
Python
# 1-D array
np.full(10,fill_value=2)
Output
PowerShell
array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
Example
Python
# 2-D array
np.full((2,3),fill_value=3)
Output
PowerShell
array([[3, 3, 3],
[3, 3, 3]])
Example
Python
# 3-D array
np.full((2,3,4),fill_value=8)
Output
PowerShell
array([[[8, 8, 8, 8],
[8, 8, 8, 8],
[8, 8, 8, 8]],
[[8, 8, 8, 8],
[8, 8, 8, 8],
[8, 8, 8, 8]]])
All of the following will give same results
- np.full(shape=(2,3,4),fill_value=8).
- np.full((2,3,4),fill_value=8).
- np.full((2,3,4),8).
eye()
- To generate identity matrix.
- Return a 2-D array with ones on the diagonal and zeros elsewhere.
Example
Python
import numpy as np
help(np.eye)
Output
PowerShell
Help on function eye in module numpy:
eye(N, M=None, k=0, dtype=<class 'float'>, order='C', *, like=None)
Return a 2-D array with ones on the diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the output.
M : int, optional
Number of columns in the output. If None, defaults to `N`.
k : int, optional
Index of the diagonal: 0 (the default) refers to the main diagonal,
a positive value refers to an upper diagonal, and a negative value
to a lower diagonal.
dtype : data-type, optional
Data-type of the returned array.
order : {'C', 'F'}, optional
Whether the output should be stored in row-major (C-style) or
column-major (Fortran-style) order in memory.
positional arguments only and keyword arguments only
- f(a,b) ==> We can pass positional as well as keyword arguments.
- f(a,/,b) ==> before ‘/’ we should pass positional arguments only for variables i.e. here for a.
- f(a,,b) ==> after ‘‘ we should pass keyword arguments only for the variables ie., here for b.
Example
Python
# both positional and keywrod arguments
def f(a,b):
print(f'The value of a :: {a}')
print(f'The value of b :: {b}')
f(10,20)
f(a=10,b=20)
Output
PowerShell
The value of a :: 10
The value of b :: 20
The value of a :: 10
The value of b :: 20
Example
Python
# position_only.py
def f1(a, /,b):
print(f'The value of a :{a}')
print(f'The value of b :{b}')
print("Calling f1(10,20)==> Valid")
f1(10,20) # valid
print("Calling f1(a=10,b=20) ==> Invalid")
f1(a=10,b=20)
# invalid because before '/' the value for variable should be passed as positional only
Output
PowerShell
Calling f1(10,20)==> Valid
The value of a :10
The value of b :20
Calling f1(a=10,b=20) ==> Invalid
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-47-743e61686e1a> in <module>
6 f1(10,20) # valid
7 print("Calling f1(a=10,b=20) ==> Invalid")
----> 8 f1(a=10,b=20)
9 # invalid because befoe '/' the value for variable should be passed as positional only
TypeError: f1() got some positional-only arguments passed as keyword argument
s: 'a'
Example
Python
def f1(a,*,b):
print(f'The value of a :: {a}')
print(f'The value of b :: {b}')
f1(a=10,b=50) #valid
f1(10,20)
# invalid because after '*' we have to provide value for variable(b) through keyword
only
Output
PowerShell
The value of a :: 10
The value of b :: 50
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-48-67b108893ea2> in <module>
3 print(f'The value of b :: {b}')
4 f1(a=10,b=50) #valid
----> 5 f1(10,20) # invalid because after '*' we have to provide value for va
riable(b) through keyword only
TypeError: f1() takes 1 positional argument but 2 were given
Syntax
- eye(N, M=None, k=0, dtype=, order=’C’, *, like=None).
Return a 2-D array with ones on the diagonal and zeros elsewhere.
- N ==> No of rows.
- M ==> No. of columns.
- K ==> Decides in which diagonal the value should be filled with 1s.
- 0 ==> Main diagonal.
- 1 ==> above the main diagonal.
- -1 ==> below the main diagonal.
Example
Python
np.eye(2,3)
Output
PowerShell
array([[1., 0., 0.],
[0., 1., 0.]])
Example
Python
np.eye(5,k=1)
Output
PowerShell
array([[1., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0.],
Example
Python
np.eye(5,k=-1)
Output
PowerShell
array([[0., 0., 0., 0., 0.,],
[1., 0., 0., 0., 0.,],
[0., 1., 0., 0., 0.,],
[0., 0., 1., 0., 0.,],
[0., 0., 0., 1., 0.,]])
eye() properties
- It will returns always 2-D arrays.
- The number of rows and number of columns need not be same.
- If we omit the ‘M’ value then the value will be same as ‘N’.
- Bydefault main diagonal contains 1s. But we can customize the diagonal which has to contain 1s.
identity()
exactly same as ‘eye()’ function except.
- It is always square matrix(The number of rows and number of columns alway same).
- only main diagonal contains 1s.
Example
Python
import numpy as np
help(np.identity)
Output
PowerShell
Help on function identity in module numpy:
identity(n, dtype=None, *, like=None)
Return the identity array.
Example
Python
# identity(n, dtype=None, *, like=None)
np.identity(3,dtype=int)
Output
PowerShell
array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!