# To access array object using index.
import numpy as np
# consider 2d array , so arr1[0,3] will try to look the 1d array at
position 0,
# so [3,2,4,7] will be returned.
# then 3rd position of [3,2,4,7] which is 7. so 7 will be printed.
arr2 = np.array([[3,2,4,7],[1,4,6,7]])
print(arr2[0,3])
#Print the last element from the 2d dim:
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('Last element from 2d dim: ', arr[0, -1])
print('fifth last element from 2d dim: ', arr[-1, -5])
# To return a slice of an array
# Slicing concept is all about to pass arrayobject[start:end:step]
# the start of slice, end is till where, step is the increments
# it returns an ndarry and then you do operations on the same.
arr2d = np.array([[1,2,3,4,5], [6,7,8,9,10],[16,17,18,19,20],
[26,27,28,29,30]])
a = arr2d[1:3]
print(a)
print(type(a))
# To iterate through the arrays using for loop similar to list
objects.
# This requires that there will be n loops for n dimensions.
# Alternative, is np.nditer() , Iterating using iterator np.nditer()
arr2d = np.array([[1,2,3,4,5], [6,7,8,9,10],[16,17,18,19,20],
[26,27,28,29,30]])
for x in np.nditer(arr2d):
print(x)
# sort arrays . Sorting returns a copy of array as an ouptu
import numpy as np
arr = np.array([[3, 2, 4], [5, 0, 1]])
print(np.sort(arr))
# np.arange is the array range function similar to range function for
list.
# In this we can instantiate an array with a set of integers
x = np.arange(12)
a = x.reshape((3, 4)) # this will create a 2 dimension array of 3 rows
and 4 columns.
print(a)
# search an element
# search will provide you an Tuple for array of all positions where
the value 4 was found.
# In case if the 4 comes twice in a position it will return twice.
# first tuple provides the 1d array positions where 4 has occured, 2nd
tuple gives the exact index position
# within the 1d array.
#
arr = np.array([[1, 2, 3], [4, 5, 6], [4, 4, 9], [10, 11, 12], [13, 4,
15], [16, 17, 18]])
newarr = np.where(arr == 4)
print(newarr)
# np.all() is a filter criteria to look at all those elements in that
array that meet the criteria
# How np.all works. similar to conditions
# if the criteria is not met by any element in the array then
# even the other row elements in those position will not be returned.
# Let's look at the condition arr < 10, this will check the elements
which is less than 10.
# Row 1, Row 2 , Row 3 all have elements value less than 10.
# but since this is not met in any elements in Row 4, Row 5, Row 6,
# Hence the output returns as an array of [False, False, False]
# That means no row satisfies the condition completely.
arr1 = np.all(arr < 10, axis = 0)
print("arr1 : " , arr1)
# arr[:,arr1] tries to extract all those rows and respective elements
where the boolean is True.
# In our above example its "False", hence its an empty array []
print(arr[:,arr1])
# Let's look at the condition arr < 2, this will check the elements
which is less than 2.
# Row 2 , Row 3, Row 4, Row 5,Row 6 all have elements value less 2 10.
# First and second elements of Row 1 does is not less than 2.
# Hence the output returns as an array of [False,False, True]
# That means out of all rows, some columns satisfy the condition
completely.
arr2 = np.all(arr > 2, axis = 0)
print("arr2 : " , arr2)
# arr[:,arr1] tries to extract all those rows and respective elements
where the boolean is True.
# In our above example its "True" in the 2nd position of each Row, so
it returns
# all the elements of that particular position.
print(arr[:,arr2])
# in case it will check if any of the elements in all rows meets the
criteria, it will return the entire array
print(arr[:, np.any(arr > 9, axis = 0)])
# Here for each rows, one of the element in that position has value
greater than 9.
print(arr[:, np.any(arr > 16, axis = 0)])
# Here for each rows, first columns across the rows do not meet the
criteria
# hence you get only the 2nd and 3rd column of the rows
# Add / Append / Delete Array Elements
arr = np.array([23,24,25,26,27])
# to add an element to an array,
# use np.insert(array variable name, position where to insert, value
to insert)
arr = np.insert(arr,4,29)
# to add an element to an array at the end i.e to append,
# use np.append(array variable name, value to insert)
arr = np.append(arr,41)
# to delete an element in the array,
# np.delete(array variable name, [which position element has to be
deleted.])
print("before delete:", arr)
arr = np.delete(arr,[0])
print("after delete:", arr)
import numpy as np
x = [1, 2, 3, 4]
y = [4, 5, 6, 7]
za = np.add(x,y)
print(za)
# It will add elelements in the corresponding position of both arrays
and return an array
# Few more operations you can try
zs = np.subtract(x,y)
zm = np.multiply(x,y)
zd = np.divide(x,y)
zp = np.power(x,y)
zsqrt = np.sqrt(y)
print("sqrt",zsqrt)
zround = np.around(zsqrt,3) # this will round to 3 decimals, if u do
not specify it will make it whole int
print("rounded off sqrt",zround)
# If we just want to do a complete sum of all elements of 1 or two
arrays. Then how?
# we use summations and product ufuncs
# summation of an array
x = np.array([1,4,8])
y = np.array([7,4,2])
xsum = np.sum(x)
ysum = np.sum(y)
zsum = np.sum([x,y]) # you have to pass more than 1 array, then it
has be in [] i.e its an array of arrays
print("sum of all elements in x",xsum)
print("sum of all elements in y",ysum)
print("sum of all elements in x and y",zsum)
# to save to a text file, it can be a 1d or 2d arrays
# to give a specific path use r'yourfilepath\filename.txt'
# loattxt is used for loading data of single data type.
import numpy as np
arr = np.array([[3, 2, 4], [5, 0, 1]])
arr1 = np.array([[21, 12, 3], [4, 35, 26], [57, 15, 29], [10, 1, 9]])
np.savetxt( r'd:\myarrfile.txt', arr1, delimiter=',' )
arr1fileload = np.loadtxt(r'd:\myarrfile.txt', delimiter=',' )
print(arr1fileload)
[[21. 12. 3.]
[ 4. 35. 26.]
[57. 15. 29.]
[10. 1. 9.]]
Self practice and reference : Below provided code snippets are some additionals ufuncs, for your
reference.
# similarly you can do for product/multiplication.
# simpler case:
x = np.array([1,4,8])
y = np.array([7,4,2])
xprod = np.prod(x)
yprod = np.prod(y)
zprod = np.prod([x,y])
print("prod of all elements in x",xprod)
print("prod of all elements in y",yprod)
print("prod of all elements in x and y",zprod)
# While doing on axis as 1, axis as 0
zprod0 = np.prod([x,y],axis=0)
zprod1 = np.prod([x,y],axis=1)
# The product row based when axis = 0
# ie (row1 col1 * row2 col1, row1 col2 * row2 col2, row1 col3 * row2
col3)
print("prod of all elements in x and y",zprod0)
# The product was columnar wise when axis is 1.
# (row1 co11*col2*col3, row2 col1*col2*col3)
print("prod of all elements in x and y",zprod1)
# This is cumulative product
x = np.array([1,4,8])
y = np.array([7,4,2])
xcumprod = np.cumprod(x)
ycumprod = np.cumprod(y)
zcumprod = np.cumprod([x,y])
print("prod of all elements in x",xcumprod)
print("prod of all elements in y",ycumprod)
print("prod of all elements in x and y",zcumprod)
# Trignometric functions
# only for references
x = [1, 2, 3, 4]
y = [16, 49, 36, 24]
zexp = np.exp(x)
print("exp",zexp)
zsin = np.sin(x)
print("sin",zsin)
zcos = np.cos(x)
print("cos",zcos)
zlog = np.log(x)
print("log",zlog)
# Python code demonstrate statistical function
# construct a marks array
marks = np.array([50.7, 52.5, 50, 58, 55.63, 73.25, 49.5, 45])
# minimum and maximum
print('Minimum and maximum marks of the students: ')
print(np.amin(marks), np.amax(marks))
# range of marks i.e. max marks-min marks
print('Range of the marks of the students: ')
print(np.ptp(marks))
# percentile
print('marks below which 70 % student fall: ')
print(np.percentile(marks, 70))
# mean
print('Mean marks of the students: ')
print(np.mean(marks))
# median
print('Median marks of the students: ')
print(np.median(marks))
# standard deviation
print('Standard deviation of marks of the students: ')
print(np.std(marks))
# variance
print('Variance of marks of the students: ')
print(np.var(marks))
# average
print('Average marks of the students: ')
print(np.average(marks))