Tuesday, 18 July 2017

Data Science & Machine Learning - 3.2 NumPy & NumPy Arrays

Hi friends,

In this post under Data Science & Machine Learning, we'll learn about NumPy Arrays. NumPy Arrays are one of the prominent reasons why NumPy library is so popular for Data Science. In this post, we'll see various ways to create and use NumPy arrays. As already discussed in the previous post, NumPy Arrays support two ways of usage i.e. as Vectors and Matrices. There are various ways to create a NumPy Arrays such as from python lists and NumPy's own built-in functions.

Note: All the commands discussed below are run in the Jupyter Notebook environment. See this post on Jupyter Notebook to know about it in detail.

Before we can begin to use the NumPy library, we need to import NumPy library in our script using the following command:

import numpy as np

Note: We write as np to avoid typing numpy every time we need to call its library functions.

NumPy & NumPy Arrays

We now see various ways to create NumPy arrays in detail.
  1. From Python Lists - NumPy supports array method to convert Python lists to NumPy Arrays. Below is an example which converts the Python list, myList, to a NumPy Array:

  2. NumPy's array() function allows us to cast any Python list to a NumPy Array. We can do the same for nested lists as well. 



  3. Using arange() function - NumPy supports arange() method to create NumPy arrays. It is similar to the range function in Python.  Here is an example for the same.


    1. Note that the arange() function creates a 1-D array by default. We can also change the step size in the arange() function just like in the range() function in Python. 

    2. Using zeros() and ones() - These methods supported by NumPy allow users to create NumPy Arrays filled with zeros and ones respectively. Both of these take a list as integers having number of rows and number of columns as the list elements. However, these also accept a single integer as parameter in which case, the column size is defaulted to 1.  Here are a few examples for the same.


    3. Generating constant arrays - NumPy library provides a method named full that allows users to create a constant NumPy array filled with a user defined value. The below example creates a 5x3 size NumPy array with value 7.

    That's it for this post friends. In the next post, we'll see various NumPy methods to generate NumPy Arrays of random numbers which will be important for working on later to perform data analysis tasks.
    Share:

    0 comments:

    Post a Comment

    Contact Me

    Name

    Email *

    Message *

    Popular Posts

    Blog Archive