Numpy Tutorial — Part 1
PYTHON· DATA SCIENCE / DATA ANALYST
Email · keycomputereducation@gmail.com
https://medium.com/@keycomputereducation
Numpy was created in 2005 by Travis Oliphant. It is open source python package and free to use. Numpy stands for Numerical Python. It is the core library for scientific computing in python. It is written in partially in Python and mainly in C/ C++.
Numpy array can be used as a Multi-Dimensional container. It is up to 50X faster than lists. It Occupies less space and convenient to use. The Array object is called ndarray.
Install Numpy
Go to Command prompt(Start>run>cmd )
Type
>>pip install numpy
Once installation is complete, go to your IDE(pycharm, jupyter etc. ) and import Numpy library it by typing
import numpy as np
Version of numpy
import numpy as np
print( np.__version__)
numpy Array
The key difference between List and numpy array is numpy array are designed to handle vectorized operations.
A Numpy array is a grid of values, all the same type, and is indexed by a tuple of non- negative integers. The number of dimensions is the rank of the array, the shape of an array is a tuple of integers giving the size of the array along each dimension.
Using array() function we can create Numpy ndarray.
Zero Dimensional
import numpy as np
arr1 = np.array(100)
print(arr1)
One Dimensional
import numpy as np
arr1 = np.array([1,2,3,4])
print(arr1)
N- Dimensional
import numpy as np
arr1 = np.array([[1,2],[3,4]])
print(arr1)
arr2 = np.array([[[1,2,3],[4,5,6]],[[5,6,7],[6,7,8]]])
print(arr2)
Type
import numpy as np
arr = np.array([1,2,3,4])
print(type(arr))
Numpy attributes
· ndim : returns an integer value that tells us how many dimension the array have
import numpy as np
a = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
print(a.ndim)
· itemsize : returns the size of each element
import numpy as np
a = np.array([1,2,3,4])
print(a.itemsize)
b = np.array(['a','b'])
print(b.itemsize)
c= np.array([1.1,2.,3.1,4.1])
print(c.itemsize)
Output:
4
4
8
· nbytes : number of bytes used to strore data
print(a.nbytes)
· size : returns total number of elements in the array
print(a.size)
· shape : returns a tuple that specifies the number of elements for each dimension of the array.
print(a.shape)
· dtypes : returns the datatype of elements stored in array
print(a.dtype)
Indexing / accession array element
You can access an array element by using its index number. Positive Index starts with Zero.
We can use negative indexing to access elements from the array.
Array →
[11,12,13,14,15]
Index ->
0, 1, 2, 3, 4
-5, -4, -3, -2, -1
One Dimension
import numpy as np
arr= np.array([11,12,13,14,15])
print(arr[0])
print(arr[-5])
Two Dimension
import numpy as np
arr = np.array([[1,2,3],[4,5,6]])
print(arr[1,1])
print(arr[-1,-2])
Download → GITHUB Link — https://github.com/keycomputer/Python/blob/main/Numpy%20Part%201.ipynb