Numpy Tutorial – Quick Guide

The NumPy library is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays.

The Numpy Library is the core library for scientific computing of Python. It provides a high-performance multidimensional array object and tools for working with these arrays.

If you want to experiment this code, visit here

Github Link

Installing Numpy

If numpy is not installed, you can use this and run in you terminal


pip install numpy

First, let’s start importing numpy


import numpy as np

Creating Arrays

We can create n-dimensional array with numpy array function.


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

#Output
[1 2 3]

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
print(b)

#Output
[[ 1.5  2.   3. ]
 [ 4.   5.   6. ]]

c = np.array([[(1.5,2,3), (4,5,6)], [(3,2,1), (4,5,6)]],dtype = float)
print(c)

#Output
[[[ 1.5  2.   3. ]
  [ 4.   5.   6. ]]

 [[ 3.   2.   1. ]
  [ 4.   5.   6. ]]]

Initial Placeholders

Let’s start creating some zeros, ones, random and empty arrays

Create an array of zeros


np.zeros((3,4))  #Create an array of zeros

#Output
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])

Create an array of ones


np.ones((2,3,4),dtype=np.int16)   #Create an array of ones

#Output
array([[[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]],

       [[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]]], dtype=int16)

Create an array of evenly spaced values (step value)


d = np.arange(10,25,5)  
print(d)

#Output
[10 15 20]

Create an array of evenly spaced values (number of samples)


np.linspace(0,10,5)  

#Output
array([ 0. ,  2.5,  5. ,  7.5, 10. ])

Create a constant array


e = np.full((2,2),7)    # Create a constant array
print(e)

#Output
[[7 7]
 [7 7]]

Create a 2X2 identity matrix


f = np.eye(2)      #Create a 2X2 identity matrix
print(f)

#Output
[[ 1.  0.]
 [ 0.  1.]]

Create an array with random values


np.random.random((2,2))    #Create an array with random values

#Output
array([[ 0.28498798,  0.76212274],
       [ 0.47272749,  0.66226621]])

Create an empty array


np.empty((3,2))       #Create an empty array

#Output
array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])

Data Types

Let’s explore some data types


np.int64   #Signed 64-bit integer types
np.float32 #Standard double-precision floating point
np.complex #Complex numbers represented by 128 floats
np.bool    #Boolean type storing TRUE and FALSE values
np.object  #Python object type
np.string_ #Fixed-length string type
np.unicode_ #Fixed-length unicode type

Inspecting Your Array


a = np.array([1,2,3])
a.shape           #Array dimensions

#Output
(3,)

a = np.array([1,2,3])
len(a)            #Length of array

#Output
3

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.ndim            #Number of array dimensions

#Output
2

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.size            #Number of array elements

#Output
6

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.dtype           #Data type of array elements

#Output
dtype('float64')

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.dtype.name      #Name of data type

#Output
'float64'

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.astype(int)     #Convert an array to a different type

#Output
array([[1, 2, 3],
       [4, 5, 6]])

Asking For Help

Put any function in the np.info() of numpy, you want the help for:


np.info(np.ndarray.dtype)

#OutPut
Data-type of the array's elements.

Parameters
----------
None

Returns
-------
d : numpy dtype object

See Also
--------
numpy.dtype

Examples
--------
>>> x
array([[0, 1],
       [2, 3]])
>>> x.dtype
dtype('int32')
>>> type(x.dtype)

Arithmetic Operations

Subtraction


a = np.array([1,2,3])
b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
g = a - b    #Subtraction
print(g)

#Output
[[-0.5  0.   0. ]
 [-3.  -3.  -3. ]]

a = np.array([1,2,3])
b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
np.subtract(a,b)  #Subtraction

#Output
array([[-0.5,  0. ,  0. ],
       [-3. , -3. , -3. ]])

Addition


a = np.array([1,2,3])
b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b + a             #Addition

#Output
array([[ 2.5,  4. ,  6. ],
       [ 5. ,  7. ,  9. ]])

a = np.array([1,2,3])
b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
np.add(b,a)    #Addition

#Output
array([[ 2.5,  4. ,  6. ],
       [ 5. ,  7. ,  9. ]])

Multiplication


a = np.array([1,2,3])
b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
a * b          #Multiplication

#Output
array([[  1.5,   4. ,   9. ],
       [  4. ,  10. ,  18. ]])

a = np.array([1,2,3])
b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
np.multiply(a,b)   #Multiplication

#Output
array([[  1.5,   4. ,   9. ],
       [  4. ,  10. ,  18. ]])

Division


a = np.array([1,2,3])
b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
a / b          #Division

#Output
array([[ 0.66666667,  1.        ,  1.        ],
       [ 0.25      ,  0.4       ,  0.5       ]])

a = np.array([1,2,3])
b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
np.divide(a,b) #Division

#Output
array([[ 0.66666667,  1.        ,  1.        ],
       [ 0.25      ,  0.4       ,  0.5       ]])

Exponential


b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
np.exp(b) #Exponentiation

#Output
array([[   4.48168907,    7.3890561 ,   20.08553692],
       [  54.59815003,  148.4131591 ,  403.42879349]])

Square Root


b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
np.sqrt(b)

#Output
array([[ 1.22474487,  1.41421356,  1.73205081],
       [ 2.        ,  2.23606798,  2.44948974]])

Different Functions


a = np.array([1,2,3])
b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
np.sin(a) #Print sines of an array
np.cos(b) #Element-wise cosine
np.log(a) #Element-wise natural logarithm

Dot Product


x = np.array([[1,2],[3,4]])
y = np.array([[1,2],[3,4]])
x.dot(y)    #Shape of both arrays should be same

#Output
array([[ 7, 10],
       [15, 22]])

Aggregate Functions


b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.sum() #Array-wise sum

#Output
21.5

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.sum(axis=0) #Column-Wise Sum

#Output
array([5.5, 7. , 9. ])

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.sum(axis=1) #Row-wise sum

#Output
array([ 6.5, 15. ])

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.min() #Array-wise minimum value

#Output
1.5

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.max(axis=0) #Maximum value of an array column wise

#Output
array([4., 5., 6.])

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.max(axis=1)  #Row Wise

#Output
array([3., 6.])

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.cumsum(axis=1) #Cumulative sum of the elements

#Output
array([[ 1.5,  3.5,  6.5],
       [ 4. ,  9. , 15. ]])

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.b.mean() #Mean

#Output
3.5833333333333335

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
np.median(b) #Median

#Output
3.5

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
np.corrcoef(b) #Correlation coefficient

#Output
array([[1.        , 0.98198051],
       [0.98198051, 1.        ]])

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
np.std(b) #Standard deviation

#Output
1.5920810978785667

Copying Arrays


>>> x = np.array([1,2,3,4])
>>> y = x
>>> x is y
True
>>> id(x), id(y)
(139814289111920, 139814289111920)
>>> x[0] = 9
>>> y
array([9, 2, 3, 4])

>>> x[0] = 1
>>> z = x[:]
>>> x is z
False
>>> id(x), id(z)
(139814289111920, 139814289112080)
>>> x[0] = 8
>>> z
array([8, 2, 3, 4])
>>> x = np.array([1,2,3,4])
>>> y = x.copy()
>>> x is y
False
>>> id(x), id(y)
(139814289111920, 139814289111840)
>>> x[0] = 9
>>> x
array([9, 2, 3, 4])
>>> y
array([1, 2, 3, 4])

Sorting Arrays


b.sort()  #Sort an array
b

#Output
array([[1.5, 2. , 3. ],
       [4. , 5. , 6. ]])

Subsetting


b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b[1]   # Select the 2nd Row

#Output
array([4., 5., 6.])

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b[1,2] #Select the element at row 1 column 2 (equivalent to b[1][2])

#Output
6.0

Slicing


b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b[0][0:2] #Select items 1 and 2 ar row 1

#Output
array([1.5, 2. ])

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b[0:2,1] #Select items at rows 0 and 1 in column 1

#Output
array([2., 5.])

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b[:1] #Select all items at row 0 (equivalent to b[0:1, :])

#Output
array([[1.5, 2. , 3. ]])

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b[ : :-1] #Reversed array 

#Output
array([[4. , 5. , 6. ],
       [1.5, 2. , 3. ]])

Boolean Indexing


b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b[b<2] #Select elements from b less than 2

#Output
array([1.5])

Transposing Array


b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
i = np.transpose(b)          #Permute array dimensions
i

#Output
array([[1.5, 4. ],
       [2. , 5. ],
       [3. , 6. ]])

i.T                          #Permute array dimensions

#Output
array([[1.5, 2. , 3. ],
       [4. , 5. , 6. ]])

Changing Array Shape


b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.ravel()                    #Flatten the array

#Output
array([1.5, 2. , 3. , 4. , 5. , 6. ])

b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
b.reshape(3,2)              #Reshape, but don’t change data

#Output
array([[1.5, 2. ],
       [3. , 4. ],
       [5. , 6. ]])

Thank You!

Paras Patidar

I am a Machine Learning and AI Enthusiast.

Add comment

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.