What is Numpy?
Numpy means
Numerical Python and It is a library in python. It helps to create multi-dimensional arrays. You can even use numpy as np by importing it. The syntax is
“import
numpy as np”
Also, It is known as ndarray.
Examples:
np.arange(0,25): It is similar
to built in function range in python.
.reshape(5,5): It helps to
convert range or 1 d array to 2d array (Matrix)
Let me consider one example to
make this more clear to you...
import numpy as np
jas=np.arange(0,25)
jas
output>> array([ 0, 1,
2, 3, 4,
5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24])
The above output indicates the
range of elements starting from zero and ending with 24. These elements are
stored in the variable named jas.
Now I am going to convert it
into 2d array by using .reshape() method.
newjas=jas.reshape(5,5)
newjas
output>>
array([[ 0, 1,
2, 3, 4],
[ 5, 6, 7,
8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
You can also perform slicing
operations for 2d arrays. It is also similar to normal slicing in python.
Now, I am gonna perform
slicing operation to grab [10,11] from the above matrix or 2d array.
newjas[2,0:2]
output>> array([10, 11])
np.random method helps to
print random integers.
np.random.rand(3): It prints
random 3 integer values
np.random.randint(3): It
prints any 1 random integer from 1 to 3
np.random.randn(5): It prints
5 different values with standard deviation
Examples :
np.random.rand(2,2)
out>>
array([[0.79726042, 0.07532593],
[0.61702185, 0.79740291]])
np.random.randn(3,3)
out>>
array([[ 1.56126572,
-0.29426117, 1.31736193],
[ 1.56405012, -1.68793157,
0.20998384],
[-0.05586385, 0.08771844,
-1.46522321]])
np.random.randint(6,10)
out>> 6
To print the maximum and
minimum values in array we can use two methods called .max() and .min()
newjas.max()
out>>
24
newjas.min()
out>>
0
We can even perform copy
operation. It helps to copy the array elements to another variable.
newnew=newjas.copy()
newnew
out>>
array([[ 0, 1,
2, 3, 4],
[ 5, 6, 7,
8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
We can make any changes to the
new copied array and it doesn’t affect the original array.
The broadcasting is also
possible here, where you can change elements in array.
newnew[1:2]=100
newnew
array([[ 0, 1,
2, 3, 4],
[ 100, 100, 100,
100, 100],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])