Class XI IP - Python List Dictionary NumpyArrays

You might also like

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

Storage of single Data values in Python

Variable
e.g a=10, name="BVM", amount=2345.90

Storage of Collection of data values in Python


DATA ITEMS val1 val2 val3 val4 val5
(collection of values)
Integer Position Index (auto maintained) – Forward 0 1 2 3 4
(available for tuple, list, array, series, rows & columns of dataframe)
Integer Position Index (auto maintained) – Backward -5 -4 -3 -2 -1
(available for tuple, list, array, series, rows & columns of dataframe)
Index Label (user defined) s1 s2 s3 s4 s5
(available for dictionary, series, rows & columns of dataframe)

Position index always starts with 0 (from left to right or from first value onward)

Backward index starts with -1 ( from right to left)

TUPLE a = ( 23,"45",-6,890,4.5 ) read only collection i.e. oncce created values cannot be changed
LIST a= [ 23,"45",-6,890,4.5 ] heterogeneous collection wherein values can be changed or deleted
ARRAY a= [ 23,45,-6,890,4 ] homogenous collection wherein values can be changed or deleted
numpy is an external package or software that we import into python software so that we can create and
manage arrays.

67 -4 0 52 16 int+float+string

mutable

Python LIST
To create a list by assigning values to a list
Only sequences such as string, tuple, set, dictionary, another list can be assigned to a list.
Numbers (int and float) are not sequences so they can't be assigned to a list lst but can be assigned to a list element lst[i].
mylist=[] print(mylist)#[]
mylist=[1,2,3,4,-2,9,7,0] print(mylist)#[1,2,3,4,-2,9,7,0]
mylist=['a','b','c','d','x','m','r','z'] print(mylist)#['a','b','c','d','x','m','r','z']
mylist=['bvm','ntl','hld','ddn'] print(mylist)#['bvm','ntl','hld','ddn']
mylist=[3.5,6.98,-47.89,0.8,2.33, 2.003] print(mylist)#[3.5,6.98,-47.89,0.8,2.33, 2.003]
mylist=[1,2,'a','b','bvm','ntl',3.5,6.98] print(mylist)#[1,2,'a','b','bvm','ntl',3.5,6.98]

mylist=[1,2,3,4,(10,20,30,40),[5,6,7,8]] print(mylist)# [1,2,3,4,(10,20,30,40),[5,6,7,8]]

To create a list using a constructor


mylist=list() print(mylist)#[]
mylist=list("hello") argument/parameter print(mylist)#['h','e','l','l','o']
mylist1=[1,2,3,4]
mylist=list(mylist1) print(mylist)#[1,2,3,4]
t1=(10,20,30,40)
mylist=list(t1) print(mylist)#[10,20,30,40]
l2=[5,6,7,8]
mylist=list(l1,t1,l2) print(mylist)#error– list() takes only 1 argument
mylist=list(l1+t1+l2) print(mylist)#error– can only concatenate list
(not "tuple") to list
mylist=list(l1+list(t1)+l2) print(mylist)#[1,2,3,4,10,20,30,40,5,6,7,8]
mylist=list(input("Enter list elements")) print(mylist)#['1','2','3'] if input is 123
mylist=list(input("Enter list elements")) print(mylist)#['1','2','3'] if input is [1,2,3]
mylist=list(int(input("Enter list elements")))
print(mylist)#error- 'int' is not iterable
if input is 123

To add elements to an existing list


mylist=list() print(mylist)#[]
mylist.append(12) print(mylist)#[12]
mylist.extend("34") print(mylist)#[12,'3','4']

770943221.docx 1
mylist.extend(67) print(mylist)#error - 'int' object is not
iterable
mylist.extend('67') print(mylist)#[12,'3','4','6','7']
mylist.extend([67,89]) print(mylist)#[12,'3','4','6','7',67,89]
mylist.extend((0,1)) print(mylist)#[12,'3','4','6','7',8,9,0,1]
mylist.insert(2,-58) print(mylist)#[12,'3',-58,'4','6','7',8,9,0,1]

Slicing a list – to access some of its elements for printing


list= [ 12, 'BVM', 78, 90.0]
0 1 2 3 #Forward Index
-4 -3 -2 -1 #Backward Index

mylist=[0,1,2,3,4,5,6,7,8,9]
print(mylist) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(mylist[0]) # 0
print(mylist[-1]) # 9
print(mylist[2:]) #[2, 3, 4, 5, 6, 7, 8, 9]
print(mylist[:2]) #[0, 1]
print(mylist[2:5]) #[2, 3, 4]
print(mylist[2:8:2]) #[2, 4, 6]
print(mylist[::2]) #[0, 2, 4, 6, 8]
print(mylist[::-1]) #[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] reverse list
print(mylist[:-5:-1]) #[9, 8, 7, 6]
print(mylist[0:-5:-1]) #[]
print(mylist[-2:-8:-2]) #[8, 6, 4]
print(mylist[2:-5]) #[2, 3, 4]
print(mylist[-2:-5]) #[]
print(mylist[-2:5]) #[]

Slicing a list – to access some of its elements for update


mylist=[0,1,2,3,4,5,6,7,8,9]
mylist[2]="x" print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9]
#[0,1,'x',3,4,5,6,7,8,9]
mylist[2]=20 print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9]
#[0,1,20,3,4,5,6,7,8,9]
mylist[2]="20" print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9]
#[0,1,'20',3,4,5,6,7,8,9]
mylist[2:]=20 print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9] #
Error:can only assign an iterable; int-X
mylist[2:]="20" print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9]
#[0,1,'2','0']
mylist[2:5]="20" print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9]
#[0,1,'2','0',5,6,7,8,9]
mylist[2:-3]="20" print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9]
#[0,1,'2','0',7,8,9]

Using loops to handle multiple elements of a list


mylist=[0,1,2,3,4,5,6,7,8,9]
for i in l:
print(i, end=' ') #0 1 2 3 4 5 6 7 8 9
for i in l:
print(i, end='-') mylist=[0,1,2,3,4,5,6,7,8,9] #0-1-2-3-4-5-6-7-8-9-
for i in l:
print(i) mylist=[0,1,2,3,4,5,6,7,8,9] # prints 0..9 vertically one on a line
for i in l:
print(mylist[i]) mylist=[0,1,2,3,4,5,6,7,8,9] # prints 0..9
vertically one on a line
for i in range(len(mylist)):
print(mylist[i]) mylist=[0,1,2,3,4,5,6,7,8,9] # prints 0..9
vertically one on a line
for i in range(len(mylist)):
print(mylist[i]*2,end="_") # 0_2_4_6_8_10_12_14_16_18_
each element is multiplied by 2
mylist=['1','2','3']
for i in range(len(mylist)):
print(mylist[i]*2,end="_") # 11_22_33_
each element is replicated twice
NOT multiplied by 2
Deleting elements of a list
del index deletes one an element at or a slice of the specified index.
list.pop(index) deletes an element at the specified index and prints it as welmylist.
list.remove(value) deletes the specified value rather than the value at the specified index.

770943221.docx 2
mylist=[0,1,2,3,4,5,6,7,8,9]
print(mylist) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
del l print(mylist)mylist=[0,1,2,3,4,5,6,7,8,9] #print(mylist) gives error after
del l;
list already removed completely
del mylist[2] print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9] #[0, 1,
3, 4, 5, 6, 7, 8, 9]
del mylist[0:2] print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9] #[2, 3,
4, 5, 6, 7, 8, 9]
del mylist[-5:-2] print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9] # [0, 1,
2, 3, 4, 8, 9]
del l [-2:-5] print(mylist)mylist=[0,1,2,3,4,5,6,7,8,9] #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
nothing deleted; invalid slice
print(mylist.pop()) mylist=[0,1,2,3,4,5,6,7,8,9]
#9;actually printed all elements till 9
print(mylist.pop(2)) mylist=[0,1,2,3,4,5,6,7,8,9]
#deletes and prints 2
print(mylist.pop(-2)) mylist=[0,1,2,3,4,5,6,7,8,9] #deletes and prints 8
mylist.remove(3) print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9] #[0, 1,
2, 4, 5, 6, 7, 8, 9]
removes value 3 not the index 3 element
mylist=['a','b','c','d']
mylist.remove('b') print(mylist) mylist=[0,1,2,3,4,5,6,7,8,9] #['a',
'c', 'd']

List Method & Functions


mylist=[0,1,2,30,4,55,6,-7,8,9]
print(len(mylist)) # 10
print(max(mylist)) # 55
print(min(mylist)) # -7

mylist.append(item) #it talks about an element being appended to the


list
mylist.extend(l1) #it talks about the list being extended with
iterables
mylist.insert(pos,item) #
mylist.remove(value) #
mylist.clear(mylist) #
mylist.pop(mylist) #
mylist.pop(index) #
mylist.index(item) #
mylist.sort() #
mylist.sort(reverse=True) #
mylist.count(item) #count the given item in the list
mylist.copy() #creates shallow copy and not a reference of a
list
#changes in the values will not be reflected in the copies

3 in [4,2,3] #True; membership test


3 not in [4,2,3] #False

mylist1==l2 #Lexicographical order; respective or same


position elements
are compared. No. of elements in l1 and l2 does not matter.
l1<l2
mylist=l1+l2 #joins two lists l1 and l2
mylist=l1*3 #replicates l1 three times

770943221.docx 3
Python DICTIONARY
Unordered collection of item where each item consists of a key and a value.
Values are mutable but keys are immutable.
Key:Value pairs can be in the form of a tuple, list or dictionary wherein items are separated by commas. Keys can't
be specified in the form of a list or dictionary as they are mutable sequences. Values can be any mutable or
immutable literals or sequences.
Keys must be unique.

Creating a dictionary by assigning values


d={} print(d)#{}
d={'k1':'v1','k2':'v2','k3':'v3'} print(d)# {'k1':'v1','k2':'v2','k3':'v3'}
d={'jan':31,'feb':28,'mar':31} print(d)# {'jan': 31, 'feb': 28, 'mar': 31}
d={5:'Number','a':'String',(1,2):'tuple'} print(d)# {5:'Number','a':'String',(1,2):'tuple'}
d={5:'Number','a':'String',[1,2]:'tuple'} print(d)# Error: unhashable type: 'list'
key cannot be mutable item such as a list
d={'v1':'a','v2':'e','v3':'i','v4':'o'} print(d)# {'v1':'a','v2':'e','v3':'i','v4':'o'}

Creating a dictionary using constructor


d=dict() print(d)#
vowels=dict(v1='a',v2='e',v3='i') print(vowels)# {'v1':'a','v2':'e','v3':'i'}
#comma-separated key=value pairs
#don't use quotes for keys as arguments
vowels=dict([['v1','a'],['v2','e'],['v3','i']]) print(vowels)# {'v1':'a','v2':'e','v3':'i'}
#key-value pairs in a list of lists
vowels=dict((['v1','a'],['v2','e'],['v3','i'])) print(vowels)# {'v1':'a','v2':'e','v3':'i'}
#key-value pairs in a tuple of lists
vowels=dict((('v1','a'),('v2','e'),('v3','i'))) print(vowels)# {'v1':'a','v2':'e','v3':'i'}
#key-value pairs in a tuple of tuples
vowels=dict({'v1':'a','v2':'e','v3':'i'}) print(vowels)# {'v1':'a','v2':'e','v3':'i'}
#comma-separated key:value pairs or
#another dictionary within {}
vowels=dict(zip(('v1','v2','v3'),('a','e','i'))) print(vowels)# {'v1':'a','v2':'e','v3':'i'}
#keys in a tuple and values in a separate
#tuple joined using zip()
vowels=dict(zip(('v1','v2','v3'),['a','e','i'])) print(vowels)# {'v1':'a','v2':'e','v3':'i'}
#keys in a tuple and values in a list
vowels=dict(zip(['v1','v2','v3'],['a','e','i'])) print(vowels)# {'v1':'a','v2':'e','v3':'i'}
#keys in a list and values in a separate
list

Nested dictionary
student={218120:{'name':'abcd','age':16,'marks':87},216415:{'name':'xyz','age':14,'marks':56}}
for i in student:
print(i,'=',student[i])
218120 = {'name': 'abcd', 'age': 16, 'marks': 87}
216415 = {'name': 'xyz', 'age': 14, 'marks': 56}

Adding key:value pairs to an empty dictionary


d=dict() #or d={}
# <dictionary>[<key>]=<value>
d['key1']='value1'
d['key2']='value2'
print(d) # {'key1':'value1','key2':'value2'}

Creating a dictionary using user input


student=dict() #or student={}
n=int(input("Enter the number of students"))
for i in range(n):
key=input("Enter Folio ")
value=input("Enter Name ")
student[key]=value
print(student)
Enter the number of students2
Enter Folio 123
Enter Name abcd
Enter Folio 456
Enter Name xyz
{'123': 'abcd', '456': 'xyz'}

770943221.docx 4
Accessing dictionary items
d={'v1':'a','v2':'e','v3':'i','v4':'o'}
print(d.keys()) # dict_keys(['v1', 'v2', 'v3', 'v4'])
print(d.values()) # dict_values(['a', 'e', 'i', 'o'])
for i in d:
print(i, end='..') # v1..v2..v3..v4..; keys
print()
for i in d:
print(d[i], end='..') # a..e..i..o..; values
d={5:'Number','a':'String',(1,2):'tuple'}
print(d) # {5:'Number','a':'String',(1,2):'tuple'}
print(d[5]) # Number
print(d['a']) # String
print(d[(1,2)]) # tuple; here key is a tuple

Updating dictionary items


d={5:'Number','a':'String',(1,2):'tuple'} print(d)# {5:'Number','a':'String',(1,2):'tuple'}
d['a']=456
d[(1,2)]="New Tuple" print(d) #{5:'Number','a':456,(1,2):'New Tuple'}

Deleting an element from a dictionary


d={5:'Number','a':'String',(1,2):'tuple'}
del d['v2'] print(d) #{'v1':'a','v3':'i','v4':'o'}
#del just removes an item
d={5:'Number','a':'String',(1,2):'tuple'}
print(d.pop('a')) #String
#pop deletes and returns the item removed
print(d.pop('a')) #Error – item with key 'a' not found
print(d.pop('a',"Not Found")) #Not Found
print(d) #{5: 'Number', (1, 2): 'tuple'}

Detecting the presence of dictionary items (membership test)


d={5:'Number','a':'String',(1,2):'tuple'}
print('a' in d) #True
print((1,2) in d) #True
print(5 not in d) #False
print('x' in d) #False

Pretty printing a dictionary


import json
d={'v1':'a','v2':'e','v3':'i','v4':'o'}
print(json.dumps(d, indent=2))
{
"v1": "a",
"v2": "e",
"v3": "i",
"v4": "o"
}
Dictionary Functions & Methods
d={'v1':'a','v2':'e','v3':'i'}
d1={'v5':'x','v2':'z'}
print(len(d)) #4
print(d.get('v2')) #e
print(d.get('v21',"Not Found")) #Not Found
print(d.items()) #dict_items([('v1','a'),('v2','e'),('v3','i')])
print(d.keys()) #dict_keys(['v1', 'v2', 'v3'])
print(d.values()) #dict_values(['a','e','i'])
d.update(d1)
print(d) #{'v1':'a','v2':'z','v3':'i','v5':'x'}
#Values of similar keys are changed
#Dissimilar keys with their values are joined
d.clear()
print(d) #{}

770943221.docx 5
Numpy
A python package that provides array or ndarray or n-dimensional array object to store multiple homogeneous
items i.e. items of the same data type. Data type of an array is called its dtype.
Used for scientific computing, data analysis and data manipulation in python.
Other packages for data analysis such as pandas, scikit-learn are built on top of Numpy.
Vectorized operation can be performed on an array – if a function is applied, it is performed on every item in the
array, rather than on the array object as a whole.
e.g.
arr+2
will add 2 to each elements of the array arr whereas
lst[2]+2
will give an error rather than adding 2 to all list items.
Size of array is immutable.
An equivalent numpy array occupies much less space than a python list of lists.

Creating a numpy array


import numpy as np
mylist=[1,2,3,4,5,6]
arr1d=np.array(mylist) print(arr1d) #[1 2 3 4 5 6]

#creates a vector or 1D array from a list


mylist=[[0,2,4,2],[3,4,5,6],[5,6,4,5]]
arr2d=np.array(mylist) print(arr2d) #[[1 2] [3 4] [5 6]]
#creates a matrix or 2D array from a list of lists
arr2df=np.array(l, dtype='float') print(arr2df) #[[1. 2.] [3. 4.] [5. 6.]]
#creates a 2D float array from a list of lists
arr2dobj=np.array(l, dtype='object') print(arr2dobj) #[[1 2] [3 4] [5 6]]
#creates a 2D object array from a list of lists
#to store items of type string,float,int etc.together
arr2dboomylist=np.array(l, dtype='bool') print(arr2dbool) #[[False True][True True][True
True]]
#creates a 2D boolean array from a list of lists
#all non-zero values are represented by True
#zeros are represented by False
NumPy - Array From Numerical Ranges
numpy.arange(start, stop, step, dtype)
Parameter:
start start of an intervamylist. If omitted, defaults to 0
stop end of an interval (not including this number)
step spacing between values, default is 1
dtype data type of resulting ndarray. If not given, data type of input is used
x=np.arange(5) #using default value 0 for start #[0 1 2 3 4]
x=np.arange(5,dtype=float) #setting dtype #[0. 1. 2. 3. 4.]
x=np.arange(10,20,2) #setting start and stop parameters #[10 12 14 16 18]

numpy.linspace(start, stop, num, endpoint, retstep, dtype)


Parameter:
start starting value of the sequence. If omitted, defaults to 0
stop end value of the sequence, included in the sequence if endpoint set to true
num number of evenly spaced samples to be generated. Default is 50
instead of step size, the number of evenly spaced values between the interval is specified
endpoint True by default, hence the stop value is included in the sequence. If false, it is not included
retstep if true, returns samples and step between the consecutive numbers
dtype data type of output ndarray
x=np.linspace(10,20,5) #[10. 12.5 15. 17.5 20.]
x=np.linspace(10,20,5,endpoint=False) #setting endpoint to false #[10. 12. 14. 16. 18.]
x=np.linspace(1,2,5,retstep=True) #finding retstep value
#(array([ 1. , 1.25, 1.5 , 1.75, 2. ]), 0.25)
#here, retstep is 0.25
Array of random values from a uniform distribution over [0, 1)in a given shape
O is included, 1 is excluded
np.random.rand(3,2)
#array([ [ 0.14022471, 0.96360618], #random
[ 0.37601032, 0.25528411], #random
[ 0.49313049, 0.94909878]]) #random
Array of random integers from low (inclusive) to high (exclusive)
numpy.random.randint(low, high=None, size=None, dtype='l')

770943221.docx 6
a = np.random.rand(4) #1d array of 4 random values
#uniform distribution in [0, 1] with mean 0.5
#array([0.66499843, 0.21296694, 0.30400306, 0.03615942])
b = np.random.randn(4) #1d array of 4 random values
#Gaussian distribution in [-inf, +inf] with mean 0 and std. dev 1
#array([-0.40164684, -0.17132923, -0.88559613, 1.27168109])
np.random.seed(1234) #Setting the random seed

a=np.random.randint(2, size=10)
#array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
a=np.random.randint(1, size=10)
#array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

np.random.randint(5,size=(2,4)) #2D array 2X4 array of int values between 0 and 4


array([ [4, 0, 2, 1],
[3, 2, 2, 0]])

array=np.random.rand(5) #1D Array


#1D Array filled with random values between 0 and 1
[ 0.84503968 0.61570994 0.7619945 0.34994803 0.40113761]
a=np.random.rand(3,4) #2D Array
#2D Array filled with random values between 0 and 1
[[ 0.94739375 0.5557614 0.69812121 0.86902435]
[ 0.94758176 0.22254413 0.21605843 0.44673235]
[ 0.61683839 0.40570269 0.34369248 0.46799524]]
a=np.full(shape=8,fill_value=3,dtype=np.int)
#1d array with value 3 repeated 8 times
#array([3, 3, 3, 3, 3, 3, 3, 3])
a=np.full(shape=(2,4),fill_value=3,dtype=np.int)
#2d array with value 3 repeated 8 times in the shape 2X4
#array([ [3, 3, 3, 3],
[3, 3, 3, 3]])
a=np.repeat(3, 10) #1D array with value 3 repeated 10 times
#array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3])
a=np.ones((3, 3)) #(3, 3) is a tuple; #2d array 3X3 with values 1s
#array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
b = np.zeros((2, 2)) #2d array 2X2 with values 0s
#array([ [0., 0.],
[0., 0.]])
c = np.eye(3) #2d array 3X3 with diagonal carrying 1s
#array([ [1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
d = np.diag(np.array([1, 2, 3, 4])) #2d array NXN with list values on diagonal
#where N is the number of items in list
#array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])
Getting details of a numpy array
import numpy as np
mylist=[[1,2],[3,4],[5,6]]
arr2d=np.array(mylist) print(arr2d) #[[1 2]
[3 4]
[5 6]]
print('Shape of 2D array: ',arr2d.shape) # Shape of 2D array: (3, 2)
print('Datatype of 2D array: ',arr2d.dtype) # Datatype of 2D array: int32
print('Size of 2D array: ',arr2d.size) # Size of 2D array: 6
print('Dimensions of 2D array: ',arr2d.ndim) # Dimensions of 2D array: 2
print('Itemsize of 2D array: ',arr2d.itemsize) # Itemsize of 2D array elements: 4 byte for int
print('Type of 2D array: ',type(arr2d)) # Type of 2D array: <class 'numpy.ndarray'>

Converting data type of array elements of a numpy array to a different type


import numpy as np
mylist=[[1,2],[3,4],[5,6]]
arr2df=np.array(l, dtype='float') print(arr2df) #[[1. 2.] [3. 4.] [5. 6.]]
arr=arr2df.astype('int') print(arr) #[[1 2] [3 4] [5 6]]
arr=arr2df.astype('int').astype('str') print(arr) #[['1' '2'] ['3' '4'] ['5' '6']]

770943221.docx 7
Numpy array Functions and Methods
import numpy as np
mylist=[[1,2],[3,4],[5,6]]
arr2d=np.array(mylist) print(arr2d) # [[1 2]
[3 4]
[5 6]]
print(arr2d.mean()) #3.5
print(arr2d.max()) #6
print(arr2d.min()) #1
print(np.amin(arr2d, axis=0)) #[1 2]; column-wise min values in the array
print(np.amax(arr2d, axis=1)) #[2 4 6]; row-wise max values in the array
print(np.cumsum(arr2d)) #[1 3 6 10 15 21]; cumulative sum
arr=arr2d.reshape(2,3) print(arr) # [ [1 2 3]
[4 5 6]]
#new shape must accommodate all elements of the array
arr=arr2d.flatten() #create a 1D array from 2D array
#it creates a shallow copy of the original array i.e.
#change in flattened array does not change parent array
print(arr) #[1 2 3 4 5 6]
arr[0]=100 print(arr) #[100 2 3 4 5 6]
print(arr2d)#[[1 2][3 4][5 6]]#no change in parent array
arr=arr2d.ravel() #create a 1D array from 2D array
#but as a reference i.e.
#change in raveled array changes the parent array
arr[0]=100 print(arr) #[100 2 3 4 5 6]
print(arr2d) #[[100 2][3 4][5 6]] #change in parent array

Converting numpy array to a python list


import numpy as np
mylist=[[1,2],[3,4],[5,6]]
arr2dobj=np.array(l, dtype='object') print(arr2dobj) #[[1 2] [3 4] [5 6]]
l2=arr2dobj.tolist() print(l2)# [[1, 2], [3, 4], [5, 6]]

Creating sequences, repetitions, arrays and random numbers using numpy

Updating Array Elements


import numpy as np
mylist=[[1,2],[3,4],[5,6]]
arr2d=np.array(l, dtype='float')
print(arr2d) #[[1. 2.][3. 4.][5. 6.]]
arr2d[1,1]=np.nan #replace [1,1] element with 'Not A Number' nan value
#works with float array since nan is a float value
arr2d[2,1]=np.inf #replace [2,1] element with 'Infinite Number' inf value
print(arr2d) #[[ 1. 2.][ 3. nan][ 5. inf]]

Array Slicing
import numpy as np
mylist=[[1,2],[3,4],[5,6]]
arr2d=np.array(l , dtype='float')
print(arr2d) #[[1. 2.] [3. 4.] [5. 6.]]
print(arr2d[:2,:2]) #prints first 2 rows and first 2 columns
#[[1. 2.] [3. 4.]]
arr = arr2d > 4 #returns an array of index and boolean values?
print(arr) #[[False False] [False False] [ True True]]
print(arr2d[arr]) #[5. 6.]
print(arr2d[::-1]) #reverse the rows of the array
#[[5. 6.] [3. 4.] [1. 2.]]
print(arr2d[::-1, ::-1]) #reverse the whole array – reverse rows and columns both
#[[6. 5.] [4. 3.] [2. 1.]]
arr2d[1,1]=np.nan #replace [1,1] element with nan value
arr2d[2,1]=np.inf #replace [2,1] element with inf value
naninfindex=np.isnan(arr2d)|np.isinf(arr2d)
#get the indexes of nan or inf values
arr2d[naninfindex]=-1 #replace nan and inf values in the array with -1
print(arr2d) #[[ 1. 2.] [ 3. -1.] [ 5. -1.]]
print('Last element from 2nd dim: ', arr2d[1, -1])
#Last element from 2nd dim: 4.0
Accessing array Elelments by Value
mylist=[[1,2,3],[4,5,6],[7,8,9]]
a=np.array(mylist)

770943221.docx 8
#[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
np.where(a==4) #returns the index of an element
#(array([1], dtype=int64), array([0], dtype=int64))

b=np.where(arr==4) #flattens the parent array and then returns index of the value
print(b) #(array([3], dtype=int64),)

a=np.array([1,2,3,4,5,6,7,8]) #[1, 2, 3, 4, 5, 6, 7, 8]
b=np.where((a>2)&(a<4)) #(array([2], dtype=int64),) #returns index of the given value
b=np.where((a>2)&(a<5)) #(array([2, 3], dtype=int64),) #returns index of given values

770943221.docx 9
Delete Numpy Array Eelements
numpy.delete(arr, obj, axis=None)

where,
arr Numpy array
obj index position or list of index positions to be deleted from numpy array arr
axis the axis along which to delete; axis=1 deletes columns, axis=0 deletes rows, axis=None deletes flattened array.
arr=np.array([4,5,6,7,8,9,10,11]) #create a Numpy array from list of numbers
arr = np.delete(arr, 2) #delete element at index position 2
[4 5 7 8 9 10 11]
arr = np.delete(arr, [1,2,3]) #delete element at index positions 1,2 and 3
[4 8 9 10 11]
arr2D = np.array([[11 ,12,13,11], [21, 22, 23, 24], [31,32,33,34]]) #create a 2D array
print(arr2D) # [[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]

arr2D = np.delete(arr2D, 1, axis=1) #delete column at index 1


# [[11 13 11]
[21 23 24]
[31 33 34]]
arr2D=np.delete(arr2D,[2,3],axis=1) #Delete column at index 2 & 3
[[11 12]
[21 22]
[31 32]]
arr2D = np.delete(arr2D, 0, axis=0) #Delete row at index 0 i.e. first row
[[21 22 23 24]
[31 32 33 34]]
arr2D=np.delete(arr2D,[1, 2],axis=0) #Delete rows at ro1 1 & 2
[[11 12 13 11]]
arr2D=np.delete(arr2D, 2) #Default index is 'None'
#2D array is flattened for deleting elements
#at the given index position i.e. 2 here
#which is an element at row number 0 and column 2
#in the 2D array
[11 12 11 21 22 23 24 31 32 33 34]

770943221.docx 10
[0,1,1,2,4,1,6,1,2,9]

mean = sum/10

median

[0,1,1,1,1,2,2,4,6,9]

mode=1

variance = (v-mean)2 /10 10 for population

9 for sample

standard deviation = variance

covariance = (x-meanOFx)*(Y-meanOFy) /10

770943221.docx 11

You might also like