@sagarsharma4244

Learn 20 Numpy keywords in 2 Minutes for Beginners

We use numpy for creating, manipulating matrices which are used in neural networks.

Check out the code yourself 🎁

Lets look at 20 most used keywords that you will need to do data science.

Creating Array

1. Add elements to an array.

a = np.array( [ 1, 2, 3 ] )

a = [1,2,3]

a = np.array( [ 1.5, 2, 3 ] )

a = [1.5,2.0,3.0]

2. Array with a range.

a = np.arange( 15 )

a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]

a = np.arange( 2, 15 )

a= [ 2  3  4  5  6  7  8  9 10 11 12 13 14]

Creating Matrices

3. Create & Add elements to matrix.

a = np.matrix( [ [1, 2], [3, 4], [2, 5] ] )

[[1 2]
 [3 4]
 [2 5]]

4. Reshape array to matrix.

a = np.arange(15).reshape(3, 5)

([[ 0,  1,  2,  3,  4],
  [ 5,  6,  7,  8,  9],
  [10, 11, 12, 13, 14]])

5. Shape of matrix.

print ( a.shape )

( 3, 5 )

6. Dimension of matrix.

print ( a.ndim )

2

7. Size of matrix/array.

print ( a.size )

15

8. Data Type of array/matrix.

print ( a.dtype.name)

int32

9. Create Zero Matrix.

a = np.zeros( ( 3, 2 ) )

[0. 0.]
[0. 0.]
[0. 0.]

10. Create Ones Matrix.

a = np.ones( ( 2, 3 ) )

[1. 1. 1.]
[1. 1. 1.]

11. Create Identity Matrix

a = np.eye( 3 )

[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]

12. Array with known Gap.

a = np.arange( 10, 30, 5 )

[10 15 20 25 30 35]

13. Array with known Elements

a = np.linspace( 10, 30, 5 )

[10. 15. 20. 25. 30.]

14. Random Martix

a = np.random.rand( 3, 2 )

[0.30306574 0.96078018]
[0.14511645 0.92897155]
[0.198439   0.7013044 ]

15. Transpose

a.T

[0.30306574 0.14511645 0.198439  ]
[0.96078018 0.92897155 0.7013044 ]

Maths with Matrices

16. Dot product

b = np.matrix([[1, 2], [3, 4], [2, 5]])
c = np.matrix([[1, 2,8], [3, 4,2]])

np.dot( b, c ) or b*c or b.dot( c )

[ 7 10 12]
[15 22 32]
[17 24 26]

17. Sum a matrix

b = np.matrix( [ [ 1, 2 ], [ 3, 4 ] ] )

print( b.sum())

10

print( b.sum(axis=1) )

[3]
[7]

18. Add two matrix.

b = np.matrix( [ [ 1, 2 ], [ 3, 4] ] )
c = np.matrix( [ [ 5, 6 ], [ 7, 8] ] )

print( np.add( b, c ) )

[ 6  8]
[10 12]

19. Minimum Value

b.min()

1

20. Maximum Value

b.max()

3

BONUS KEYWORDS

21. Squareroot

b = np.matrix( [ [ 1, 2 ], [ 3, 4] ] )

print( np.sqrt( b ) )

[1.         1.41421356]
[1.73205081 2.        ]

Iterate

for row in b: 
print( row )
[[1 2]]
[[3 4]]

23. Flatten

b = np.matrix( [ [ 1, 2 ], [ 3, 4 ] ] )

b.flatten()

[[1 2 3 4]]

24. Floor

b = np.matrix( [ [ 1.5, 2.8 ], [ 3.45, 4.1 ] ] )

np.floor( b )

[1. 2.]
[3. 4.]

25. Split into parts

a = np.arange( 15 )

np.split( a, 5 )

array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8]), array([ 9, 10, 11]), array([12, 13, 14])

26. Join sequence of arrays | Concatenate

b = np.matrix( [ [ 1, 2 ], [ 3, 4] ] )
c = np.matrix( [ [ 5, 6 ], [ 7, 8] ] )

np.concatenate((b,c), axis=0)

[1 2 5 6]
[3 4 7 8]

np.concatenate((b,c), axis=1)

[1 2 5 6]
[3 4 7 8]

Leave a Reply

Your email address will not be published. Required fields are marked *