Numpy 2: Indexing , Slicing

Numpy is also incredibly fast, as it has bindings to C libraries. First importing numpy as alias it as np to use np instead of numpy to make to code shorter.

In [1]:
import numpy as np

Lets create a two dimensional array. First we are creating two dimensional array then converting it to numpy array.

In [2]:
python_list = [[1,2,3],[4,5,6]]
		numpy_arr = np.array(python_list)
		print("*" * 30)

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

See the difference between a general python list and numpy two dimensional array.
Now We are declaring numpy_arr to arr1 and arr2 to square of the arr1. We can perform any mathmatical operations between two numpy arrays like below.

In [3]:
arr1 = numpy_arr
		arr2 = arr1*arr1
		print("*" * 30)
		print("*" * 30)
		print("*" * 30)
		print("*" * 30)

[[1 2 3]
		 [4 5 6]]
		[[ 1  4  9]
		 [16 25 36]]
		[[ 0  2  6]
		 [12 20 30]]
		[[ 1.  2.  3.]
		 [ 4.  5.  6.]]
		[[0 0 0]
		 [0 0 0]]

Lets see some Built in methods


Return evenly spaced values within a given interval. It can have three parameters (first value, last value,increment/decrement)

In [4]:
arr1 = np.arange(20)#from 0 to 19 
		arr2 = np.arange(20,40)#from 20 to 39
		arr3 = np.arange(20,40,3)#starting from 20 and increment by 3 ending at 39

[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
		[20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39]
		[20 23 26 29 32 35 38]


In [6]:
arr = np.arange(1,11)#creating a simple array

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

In [7]:


Lets print values 5 6 7

In [9]:
arr[4:7] # arr[row,column+1]

array([5, 6, 7])


Numpy arrays are different from a normal Python list because of their ability to broadcast:

In [10]:
#Setting a value with index range (Broadcasting)


array([100, 100, 100, 100, 100,   6,   7,   8,   9,  10])

In [11]:
# Reset array, we'll see why I had to reset in  a moment
		arr = np.arange(0,11)


array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

Look carefully

In [12]:
#Important notes on Slices
		slice_of_arr = arr[0:6]

		#Show slice

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

In [13]:
#Change Slice

		#Show Slice again

array([99, 99, 99, 99, 99, 99])

Now note the changes also occur in our original array!

In [14]:

array([99, 99, 99, 99, 99, 99,  6,  7,  8,  9, 10])

Data is not copied, it’s a view of the original array! This avoids memory problems!

In [16]:
#To get a copy, need to be explicit
		arr_copy = arr.copy()


array([99, 99, 99, 99, 99, 99,  6,  7,  8,  9, 10])

In [ ]:

Code is read a million times, written once

Code is read more often than it is written. Many people start coding without think about the algorithm. Some try to put comments more than code and think it is good. But a clean code is self documented. Lets have an example:

Above code has a lot of comments but little time consuming to understand but the same code can be written as below:

It does not have comments but still understandable to everyone.

So , when should we add comments? When the code is complex and not easily understandable or may be confused.

Code should be modular / independent-

Try to put less global variables and no code should spread all over the place. Classes and functions makes code more reusable.Modular code is easy to test, easy to debug, easy to extend. That’s because if a part of the code goes out of date, you can update that, without worrying about breaking a million other things.

If you go work for any of the top software companies, only about 30% of your time will be spent coding. For an average project, you will spend:

  • 30-40% of your time designing the solution. Yes, this much. The more time you spend early on, the less you need to spend fixing bugs later.
  • Another 30-40% writing the code, which includes writing tests.
  • 10-20% debugging and testing.
  • 10% in code reviews.

Coding is an art. Being proud of your work, doing work like an artisan is what separates us from code monkeys.

Say you hired someone to build our home. The builder turns up, his pants hanging down to his ass, cheap rolled up cigarette hanging from his mouth,  and says “Yup, we’ll build your house in a week.”

And he starts throwing bricks willy nilly, in the shape of a wall. But a few days later, he realises he is going at a 30% angle, so throws everything down and starts again. A few days later, he realises he built a wall where there should have been a window. The builder laughs and says, “Mistakes happen. What are you gonna do?”

What will you do? Will you ask him why he didn’t design blueprints of the house before he started throwing bricks around?

“Hey, I’m a builder, not a designer,” he says.

Do you see now how many business owners see programmers? Just like that builder, pants hanging down, boasting, “Yeah, we’ll build that website in a week. No problem.”

This is a mix post but might be helpful for the beginners who is starting their coding career. Cheers!!


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!