Python NumPy Tutorial – NumPy ndarray & NumPy Array

1. Python NumPy Tutorial – Objective

In our last Python Library tutorial, we studied Python SciPy. Now we are going to study Python NumPy. In this NumPy tutorial, we are going to discuss the features, Installation and NumPy ndarray. Moreover, we will cover the data types and array in NumPy.
So, let’s begin the Python NumPy Tutorial.

Python NumPy Tutorial - NumPy ndarray & NumPy Array

Python NumPy Tutorial – NumPy ndarray & NumPy Array

2. What is NumPy?

A library for Python, NumPy lets you work with huge, multidimensional matrices and arrays. Along with that, it provides a gamut of high-level functions to perform mathematical operations on these structures. Here is a short brief about it:

  • Author- Travis Oliphant
  • First Release- 1995 (Released as Numeric; Changed to NumPy in 2006)
  • Stable Release- June, 2018
  • Written in- Python Programming, C

Python NumPy is cross-platform and BSD-licensed. We often use it with packages like Matplotlib and SciPy. This can be seen as an alternative to MATLAB. The term ‘Numpy’ is a portmanteau of the words ‘NUMerical’ and ‘PYthon’.
Do you know about Python Matplotlib 

3. Numpy Tutorial – Features of Numpy

In this Python NumPy Tutorial, we are going to study the feature of NumPy:

  • NumPy stands on CPython, a non-optimizing bytecode interpreter.
  • Multidimensional arrays.
  • Functions and operators for these arrays.
  • Python Alternative to MATLAB.
  • ndarray- n-dimensional arrays.
  • Fourier transforms and shapes manipulation.
  • Linear algebra and random number generation.

4. Numpy Tutorial – How to Install NumPy?

You can use pip to install numpy-

pip install numpy

Then you can import it as-

>>> import numpy as np

5. Numpy Tutorial – NumPy ndarray

This is one of the most important features of numpy. ndarray is an n-dimensional array, a grid of values of the same kind. A tuple of nonnegative integers indexes this tuple. An array’s rank is its number of dimensions. Let’s take a few examples.

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

<class ‘numpy.ndarray’>

>>> a.shape

(3,)

>>> a[0],a[2]

(1, 3)

>>> a[1]=5
>>> a

array([1, 5, 3])
Do you know the Different Steps to Learn Python for Data Science
As you can see, the array’s shape is (3,). What happens when we build an array of more than one dimension? Let’s see.

>>> b=np.array([[2,7,9],[5,1,3]])
>>> b

array([[2, 7, 9],
[5, 1, 3]])

>>> b[0,1]

7

>>> b.shape

(2, 3)

>>> b.size

6

a. How to Create NumPy Array?

The following lines of code create a few more arrays:

>>> np.arange(7) #This is like range in Python

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

>>> np.random.random((3,3)) #Fills in random values

array([[0.56074267, 0.67303599, 0.65973007],
[0.37222497, 0.13230271, 0.40858618],
[0.74455771, 0.52119999, 0.6927821 ]])

>>> np.ones((2,3))

array([[1., 1., 1.],
[1., 1., 1.]])

>>> np.zeros((1,2))

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

>>> np.eye(3) #Identity matrix

array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])

>>> np.full((3,2),7) #Matrix of constants

array([[7, 7],
[7, 7],
[7, 7]])

>>> np.linspace(1,2,4) #4 values spaced evenly between, and including, 1 and 2.

array([1. , 1.33333333, 1.66666667, 2. ])

>>> np.empty([2,3]) #Empty array

array([[1., 0., 3.],
[0., 4., 0.]])

b. Some Parameters

>>> np.array([1,3,4],ndmin=3) #Minimum dimension

array([[[1, 3, 4]]])

>>> np.array([1,3,4],dtype=complex) #Data type

array([1.+0.j, 3.+0.j, 4.+0.j])
Read about Serialization in Python with Example

6. Numpy Tutorial – Data Types

As we’ve said before, a NumPy array holds elements of the same kind. If while creating a NumPy array, you do not specify the data type, NumPy will decide it for you. We have the following data types-
bool_, int_, intc, intp, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float_, float16, float32, float64, complex_, complex64, complex128
We can confirm:

>>> np.dtype(np.int32)

dtype(‘int32’)

>>> np.dtype('i4')

dtype(‘int32’)

>>> np.dtype('i8')

dtype(‘int64’)

7. Functions of NumPy Array

Let’s take a look at all that we can do to an array and what more we can find out about it.

>>> a=np.array([[1,2,3],[4,5,6]])
>>> a.reshape(3,2)

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

>>> a.ndim #Number of array dimensions

2

>>> np.array([[1,2,3],[4,5,6]]).itemsize #Length of each element in bytes

4

>>> np.array([[1,2,3],[4,5,6]],dtype=np.int8).itemsize

1

>>> a

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

>>> a.flags

C_CONTIGUOUS: True
F_CONTIGUOUS: False
OWNDATA: True
WRITEABLE: True
ALIGNED: True
WRITEBACKIFCOPY: False
UPDATEIFCOPY: False

8. Numpy Array Indexing

It is possible to slice you NumPy arrays- with multiple slices for multidimensional arrays.

>>> a=np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> b=a[:2,1:3]
>>> b

array([[2, 3],
[5, 6]])

>>> a[1,2]

6

>>> b[0,0]=79
>>> a

array([[ 1, 79, 3],
[ 4, 5, 6],
[ 7, 8, 9]])
Read about Python Forensics – Hash Function, Virtualization
As you can see, changes to a slice modify an original.

>>> a[1,:]

array([4, 5, 6])

>>> a[1:2,:]

array([[4, 5, 6]])

>>> a[:,1]

array([79, 5, 8])

Python NumPy Tutorial - NumPy Array Index

Python NumPy Tutorial – NumPy Array Index

a. Integer Indexing

It is possible to create an array from another.

>>> a=np.array([[1,2],[3,4],[5,6]])
>>> a[[0,1,2],[0,1,0]] #Prints elements at [0,0], [1,1], and [2,0]

array([1, 4, 5])
Let’s pick elements-

>>> a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
>>> b = np.array([0, 2, 0, 1])
>>> b

array([0, 2, 0, 1])

>>> a[np.arange(4), b]

array([ 1, 6, 7, 11])

>>> a[np.arange(4), b]+=10
>>> a

array([[11, 2, 3],
[ 4, 5, 16],
[17, 8, 9],
[10, 21, 12]])

b. Boolean Indexing

This will let you pick elements that satisfy a condition.

>>> a=np.array([[1,2],[3,4],[5,6]])
>>> boolean=(a>3)
>>> boolean

array([[False, False],
[False, True],
[ True, True]])

>>> a[boolean]

array([4, 5, 6])
Let’s Read about Python Zipfile – Benefits, Modules, Objects 

Python Interview Questions

9. Mathematical Functions on Arrays in NumPy

Let’s now look at some mathematical functions to call on arrays.

>>> a=np.array([[1,2,3],[4,5,6]])
>>> b=np.array([[7,8,9],[10,11,12]])
>>> np.add(a,b) #a+b does the same

array([[ 8, 10, 12],
[14, 16, 18]])

>>> np.subtract(a,b) #Same as a-b

array([[-6, -6, -6],
[-6, -6, -6]])

>>> np.multiply(a,b) #a*b works too

array([[ 7, 16, 27],
[40, 55, 72]])

>>> np.divide(a,b) #Same as a/b

array([[0.14285714, 0.25 , 0.33333333],
[0.4 , 0.45454545, 0.5 ]])

>>> np.sqrt(a) #Produces square root

array([[1. , 1.41421356, 1.73205081],
[2. , 2.23606798, 2.44948974]])

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

10

>>> np.sum(a,axis=0) #Sum of each column

array([4, 6])

>>> np.sum(a,axis=1) #Sum of each row

array([3, 7])
To transpose this matrix:

>>> a.T

array([[1, 3],
[2, 4]])

>>> np.array([1,3,2]).T #NOP

array([1, 3, 2])
Some functions that operate on a larger context-

>>> x=np.array([[1,2],[3,4]])
>>> y=np.array([[5,6],[7,8]])
>>> v=np.array([9,10])
>>> w=np.array([11,12])
>>> v.dot(w) #Same as np.dot(v,w)

219

>>> x.dot(v)

array([29, 67])

>>> x.dot(y)

array([[19, 22],
[43, 50]])
So, this was all about Python NumPy Tutorial. Hope you like our explanation.

10. Python NumPy Tutorial – Conclusion

Hence, in this Python NumPy Tutorial we studied, how to install NumPy, NumPy ndarray. In addition, we discussed NumPy Array with its Functions and data types. This sums it up for NumPy. Got anything else to add? Drop it in the comments below.
Related Topic- Image Processing with SciPy and NumPy in Python
For reference

5 Responses

  1. birajdar pintu says:

    Thanku sir as compare to other tutorial your tutorial easily understand definately anyone student read

    • DataFlair Team says:

      Hi Birajdar,
      We feel motivated when our loyal reader appriciate the efforts, we made in our every Python tutorial. Hope, you are exploring other Python articles.
      Do share with your peer groups.
      Regards,
      DataFlair

  2. remya says:

    step no 8 , should it be a[0, 1] = 79 , in order to get [[ 1 79 3]
    [ 4 5 6]
    [ 7 8 9]] as an output ?

    • DataFlair Team says:

      Hi Remya,
      Thanks for the comment on Python Numpy Tutorial. Changing that value in b also changes it for a, since both points to the same object.
      Hope, now you get it.
      Regards,
      DataFlair

  3. kishan yadav says:

    i am getting this kind of error how to resolve this
    import sklearn
    Traceback (most recent call last):
    File “”, line 1, in
    File “C:\Users\kishan yadav\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\__init__.py”, line 64, in
    from .base import clone
    File “C:\Users\kishan yadav\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\base.py”, line 11, in
    from scipy import sparse
    File “C:\Users\kishan yadav\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\sparse\__init__.py”, line 231, in
    from .csr import *
    File “C:\Users\kishan yadav\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\sparse\csr.py”, line 15, in
    from ._sparsetools import csr_tocsc, csr_tobsr, csr_count_blocks, \
    ImportError: DLL load failed: The specified module could not be found.
    >>> from .base import clone
    Traceback (most recent call last):
    File “”, line 1, in
    ModuleNotFoundError: No module named ‘__main__.base’; ‘__main__’ is not a package
    >>> pip install clone

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.