Numpy 1 : Creating Arrays

Numpy, short for Numerical Python, is the fundamental package required for high
performance scientific computing and data analysis. It uses standard mathematical function for fast operation on entire list without writing any loops.

Here is an example of how numpy ease our work , don’t worry about understanding the code.

We can see every item in the list is squared just by typing new_array*new_array. On the other hand general python code will through an error if we try to do similar task like print(my_list*my_list) .

To use numpy we have to import the numpy module by typing import numpy . To shorten our wok we can say import numpy as np . By typing this we can use numpy function by np instead of numpy.

Let’s see an example on how to create a numpy array:

  1. At first we imported numpy as np.
  2. We have made a list of numbers containing 1 to  9.
  3. To convert a list into an numpy array we have to use numpy.array(list_name). So we defined the new array by np.array(our_list).
  4. And finally printed the array to check.

Let’s recall some basic python 2D list operations. To combine two list we just do like, new_list = [first_list,second_list]. This will make our new_list a 2 dimensional list. To know the shape of the our 2D list we can use numpy. Numpy use a shape function to determine the shape of the array just like below:

Can you guess the output?? Yes, it outputs 2,9 as row,column.

numpy.size(array_name) – returns the total size of the array

array_name.shape – returns the shape of the array in row,column

array_name.dtype – returns the data type of the array that it carries and it tries to infer good data type.

Numpy helps to create arrays with all the values being ‘0’ or ‘1’. To create an array containing all zeros we can just call numpy.zeros(length). To create an array containing all ones we can just call numpy.ones(length)

Try to play with numpy and do some arithmetic operations with it. Good Luck!