numpy(Python for data science)
In [1]:
import numpy as np
In [2]:
arr=np.array([[1,2,3],[4,5,6]])
In [3]:
arr #int array, element seperated by commas
Out[3]:
In [4]:
np.ndim(arr)
Out[4]:
In [5]:
arr.ndim
arr.size
arr.shape
arr.dtype
Out[5]:
In [6]:
print(arr.ndim,arr.size,arr.shape,arr.dtype)
In [13]:
print("dimension :{}\nsize : {}".format(arr.ndim,arr.size))
In [14]:
arr_dict={"dimension":arr.ndim,"size":arr.size,"shape":arr.shape,"data-type":arr.dtype}
for keys in arr_dict:
print(keys+" : ",arr_dict[keys])
In [16]:
arr=np.array([[1,2,3],[4,5,6]],dtype=float) # float array, element seperation without commas
print(arr)
In [21]:
zero_arrays_lst=list([np.zeros(3,4),np.zeros(5),np.zeros(1,2),np.zeros(2,1)])
for i in range(len(zero_arrays_lst)):
print(i+1," : ",zero_arrays_lst[i])
In [22]:
np.zeros(3,4)
In [23]:
np.zeros((3,4)) # need to pass in a tuple
Out[23]:
In [27]:
zero_arrays_lst=list([np.zeros((3,4)),np.zeros((5)),np.zeros((1,2)),np.zeros((2,1))])
for i in range(len(zero_arrays_lst)):
print(i+1," : ",zero_arrays_lst[i],'\n')
In [30]:
# Create a constant value array of complex type
np.full((3,4),10,dtype="complex")
Out[30]:
In [32]:
np.ones((3,4))
Out[32]:
In [40]:
np.arange(1,30,6) # from 1 to 30 with steps of 6
Out[40]:
In [41]:
# Create a sequence of 10 values in range 0 to 5
np.linspace(0,5,10)
Out[41]:
In [42]:
np.linspace(0,10,4) #10/3 then add it from start for next
# start 0 and end 10 fix
Out[42]:
In [51]:
np.linspace(2,16,4) #(16-2)/3 then add it from start(i.e 2+....) for next
Out[51]:
In [53]:
arr=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
print("original array : \n",arr,'\n')
print("reshaped array : \n",arr.reshape(2,6))
In [54]:
# Reshaping 3X4 array to 2X2X3 array
arr.reshape(2,2,3) # 2(no of second bracket decided by first element) banenge 2X3 =>3D
Out[54]:
In [55]:
arr.reshape(1,4,3) # 1 banenge 4X3 =>3D
Out[55]:
In [56]:
arr.reshape(2,3,2) # 2 banenge 3X2
Out[56]:
In [3]:
import numpy as np
arr=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
arr.reshape(4,3,1) # 4 banenge 3X1
Out[3]:
In [4]:
arr=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]])
arr.reshape(4,2,3) # 4 banenge 2X3
Out[4]:
In [5]:
arr.flatten()
Out[5]:
In [6]:
arr.flatten('F') # column wise from oriinal declared array
# also see in your screenshots or visit
# https://bit.ly/2OxK5J6
Out[6]:
In [11]:
arr.ravel() # for ravel visit https://bit.ly/2DRTBVr
Out[11]:
In [12]:
arr.ravel('F')
Out[12]:
In [13]:
# for flatten vs ravel visit
#https://www.geeksforgeeks.org/differences-flatten-ravel-numpy/
# a.ravel():
# (i) Return only reference/view of original array
# (ii) If you modify the array you would notice that the value of original array also changes.
# (iii) Ravel is faster than flatten() as it does not occupy any memory.
# (iv) Ravel is a library-level function.
# a.flatten() :
# (i) Return copy of original array
# (ii) If you modify any value of this array value of original array is not affected.
# (iii) Flatten() is comparatively slower than ravel() as it occupies memory.
# (iv) Flatten is a method of an ndarray object.
In [15]:
print(arr,"\n")
print("tranpose of arr :\n",arr.T)
In [22]:
# maximum element of array
print ("Largest element is:", arr.max())
print ("Row-wise maximum elements:",
arr.max(axis = 1))
# minimum element of array
print ("Column-wise minimum elements:",
arr.min(axis = 0))
# sum of array elements
print ("Sum of all array elements:",
arr.sum())
# cumulative sum along each row
print ("Cumulative sum along each row:\n",
arr.cumsum(axis = 1))
In [23]:
a = np.array([[1, 2],
[3, 4]])
b = np.array([[4, 3],
[2, 1]])
# add arrays
print ("Array sum:\n", a + b)
# multiply arrays (elementwise multiplication)
print ("Array multiplication:\n", a*b)
# matrix multiplication
print ("Matrix multiplication:\n", a.dot(b))
In [26]:
arr=np.array([[4,1,8],[6,2,5],[9,7,3]])
np.sin(arr) # similarly np.exp(arr) np.sqrt(a)
Out[26]:
In [30]:
# sorted array
print ("Array elements in sorted order:\n",
np.sort(arr, axis = None))
# sort array row-wise
print ("Row-wise sorted array:\n",
np.sort(arr, axis = 1))
# specify sort algorithm
print ("Column wise sort by applying merge-sort:\n",
np.sort(arr, axis = 0, kind = 'mergesort'))
In [39]:
# Example to show sorting of structured array
# set alias names for dtypes
dtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)] # if use only s no letter of name shown for s1 one letter shown
# Values to be put in array
values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7),
('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)]
# Creating array
arr = np.array(values, dtype = dtypes)
print ("\nArray sorted by names:\n",
np.sort(arr, order = 'name'))
print ("Array sorted by grauation year and then cgpa:\n",
np.sort(arr, order = ['grad_year', 'cgpa']))
In [40]:
import numpy as np
# make an array with numpy
gfg = np.array([1, 2, 3, 4, 5])
# applying ndarray.__rshift__() method => binary value nikalkar right shift
#using 2 right shift e.g 1 is 001=>0, 2=10=>1, 3=011=>0, 4=100=>1, 5=101=>1
print(gfg.__rshift__(2))
In [41]:
gfg = np.array([[1, 2, 3, 4, 5],
[6, 5, 4, 3, 2]])
print(gfg.__rshift__(1))
# 1 right shift, 4=100=>10=2, 5=101=>10=2, 6=110=>11=3
In [42]:
gfg = np.array([1, 2, 3, 4, 5, 6])
# applying numpy.__lt__() method
print(gfg.__lt__(4)) # kaunsa element 4 se smaller hai uske liye True
In [44]:
gfg = np.array([[1, 2, 3, 4, 5, 6],
[6, 5, 4, 3, 2, 1]])
print(gfg.__lt__(4))
In [48]:
print('Right shift 40 by two positions:')
print(np.right_shift(40,2))
print('\n')
print('Binary representation of 40:')
print(np.binary_repr(40, width = 8) )
print('\n')
print('Binary representation of 10\n')
print(np.binary_repr(10, width = 8) )
In [49]:
gfg = np.array([1, 2, 3, 4, 5])
print(gfg.__pow__(3))
In [50]:
gfg = np.array([[1, 2, 3, 4, 5],
[6, 5, 4, 3, 2]])
print(gfg.__pow__(2))
In [52]:
gfg = np.array([1, 2, 3, 4, 5, 6])
# applying numpy.__eq__() method
print(gfg.__eq__(4)) # True jo 4 ke equal hai
In [53]:
gfg = np.array([1, 2, 3, 4, 5])
# applying ndarray.__divmod__() method
print(gfg.__divmod__(3)) # first array gives quatient , second gives remainder
In [54]:
gfg = np.array([1, 2, 3, 4, 5])
# applying ndarray.__invert__() method
print(gfg.__invert__()) # gives -(element+1)
In [56]:
gfg = np.array([1, 2.5, 3, 4.8, 5])
# applying ndarray.__mod__() method
print(gfg.__mod__(2)) # gives remainder
In [58]:
gfg = np.array([1, 2, 3, 4, 5, 6])
# applying numpy.__ge__() method
print(gfg.__ge__(4)) # True for element>=4
In [59]:
gfg = np.array([1.2, 2.6, 3, 4.5, 5])
# applying ndarray.__iadd__() method
print(gfg.__iadd__(5)) # gives element+5
In [60]:
gfg = np.array([1, 2.5, 3, 4.8, 5])
# applying ndarray.__floordiv__() method
print(gfg.__floordiv__(2)) # division ke baad floor value
# 1/2=0.5=>0, 2.5/2=1.25=>1, 3/2=1.5=>1, 4.8/2=2.4=>2, 5/2=2.5=>2
In [62]:
gfg = np.array([[1, 2, 3, 4.45, 5],
[6, 5.5, 4, 3, 2.62]])
# applying ndarray.__truediv__() method
print(gfg.__truediv__(3))
In [65]:
gfg = np.array([[1, 2, 3, 4, 5],
[6, 5, 4, 3, 2]])
# applying ndarray.__add__() method
print(gfg.__add__(5)) # gives element+5
# similarly can use __sub__(5) =>element+5, isub, mul ,imul , and , xor , or ,etc.
In [67]:
gfg = np.array([1, -2, 3, 4, 5, 6])
# applying numpy.__neg__() method
print(gfg.__neg__()) # gives -(element)
In [69]:
gfg = np.array([1, 2, 3, 4, 5])
# applying ndarray.__lshift__() method
print(gfg.__lshift__(2))
# e.g 1=>001=>100=4, 5=00101=>10100=20
In [70]:
gfg = np.array([1, 2, 3, 4, 5, 6])
# applying numpy.__gt__() method
print(gfg.__gt__(3)) # stands for greater than , True for element>3
In [73]:
gfg = np.array([[1, 2, 3, 4, 5, 6],
[6, 5, 4, 3, 2, 1]])
# applying numpy.__le__() method
print(gfg.__le__(4)) # stands for less than , True for element<4
In [74]:
gfg = np.array([1, -2, 3, 4, 5, 6])
# applying numpy.__pos__() method
print(gfg.__pos__()) # element*1 i.e same as given array
In [75]:
# Python program to demonstrate a need of NumPy
list1 = [1, 2, 3, 4 ,5, 6]
list2 = [10, 9, 8, 7, 6, 5]
# Multiplying both lists directly would give an error.
print(list1*list2)
In [76]:
list1 = [1, 2, 3, 4, 5, 6]
list2 = [10, 9, 8, 7, 6, 5]
# Convert list1 into a NumPy array
a1 = np.array(list1)
# Convert list2 into a NumPy array
a2 = np.array(list2)
print(a1*a2)
In [77]:
# Create a sequence of integers from 10 to 1 with a step of -2
a = np.arange(10, 1, -2)
print("\n A sequential array with a negative step: \n",a)
# Indexes are specified inside the np.array method.
newarr = a[np.array([3, 1, 2 ])]
print("\n Elements at these indices are:\n",newarr)
In [78]:
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
# Index values can be negative.
arr = x[np.array([1, 3, -3])]
print("\n Elements are : \n",arr)
In [79]:
# Arrange elements from 0 to 19
a = np.arange(20)
print("\n Array is:\n ",a)
# a[start:stop:step]
print("\n a[-8:17:1] = ",a[-8:17:1])
# The : operator means all elements till the end.
print("\n a[10:] = ",a[10:])
In [85]:
# Python program for indexing using basic slicing with ellipsis
import numpy as np
# A 3 dimensional array.
b = np.array([[[1, 2, 3],[4, 5, 6]],
[[7, 8, 9],[10, 11, 12]]])
print(b[...,1]) #Equivalent to b[: ,: ,1 ]
print('\nanother is \n\n',b[...,2])
In [86]:
# You may wish to select numbers greater than 50
import numpy as np
a = np.array([10, 40, 80, 50, 100])
print(a[a>50])
In [90]:
# You may wish to square the multiples of 40
a = np.array([10, 40, 80, 50, 100])
print(a[a%40==0]**2)
In [94]:
# You may wish to select those elements whose
# sum of row is a multiple of 10.
b = np.array([[5, 5],[4, 5],[16, 4]])
sumrow = b.sum(-1)
print(b[sumrow%10==0])
In [96]:
np.random.rand(5)
Out[96]:
In [98]:
np.random.rand(5)
Out[98]:
In [100]:
np.random.rand(4,4)
Out[100]:
In [101]:
np.random.randn(5)
Out[101]:
In [103]:
np.random.randn(4)
Out[103]:
In [104]:
np.random.randint(5)
Out[104]:
In [106]:
np.random.randint(1,10)
Out[106]:
In [107]:
np.random.randint(1,10)
Out[107]:
In [108]:
np.random.randint(1,10)
Out[108]:
In [109]:
np.random.randint(1,50)
Out[109]:
In [116]:
np.random.randint(1,50)
Out[116]:
In [117]:
np.random.randint(1,50,10)
Out[117]:
In [118]:
np.random.randint(1,50,10)
Out[118]:
In [119]:
np.random.randint(1,100,10)
Out[119]:
In [120]:
np.random.randint(1,50,10)
Out[120]:
In [121]:
np.eye(4)
Out[121]:
In [122]:
np.eye(2)
Out[122]:
In [126]:
np.eye(3,4) # 3X4 => upto square matrix 3X3 identity next column all 0
Out[126]:
In [128]:
arr = np.array([25, 1.33, 1, 1, 100])
print('Our array is:')
print(arr)
print('\nAfter applying reciprocal function:')
print(np.reciprocal(arr))
arr2 = np.array([25], dtype = int)
print('\nThe second array is:')
print(arr2)
print('\nAfter applying rec')
In [129]:
arr = np.array([5, 10, 15])
print('First array is:')
print(arr)
print('\nApplying power function:')
print(np.power(arr, 2))
print('\nSecond array is:')
arr1 = np.array([1, 2, 3])
print(arr1)
print('\nApplying power function again:')
print(np.power(arr, arr1))
In [130]:
arr = np.array([5, 15, 20])
arr1 = np.array([2, 5, 9])
print('First array:')
print(arr)
print('\nSecond array:')
print(arr1)
print('\nApplying mod() function:')
print(np.mod(arr, arr1))
print('\nApplying remainder() function:')
print(np.remainder(arr, arr1))
In [133]:
# input two matrices
mat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])
mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7])
# This will return dot product
res = np.dot(mat1,mat2)
# print resulted matrix
print(res)
In [ ]:
Comments
Post a Comment