Numpy on Python


This package helps us to create arrays and matrices. The main difference between arrays and matrices can be determined by dimensions. Matrix is a 2d array, but the array itself can be a 1d vector or higher N dimensions.

Here are some examples we can take a look at. First, let’s suppose we want a 1d array with 25 elements ranging from 0 to 24. We then reshape the vector into a 5 by 5 matrix.

# Create a 1d array ranging from 0 to 24
np.arange(25)
array([ 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])


# Reshape the 1d array to 5 by 5 matrix arr.reshape(5,5)
array([[ 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]])


Now we want to select values from the array. Let’s use an example by using conditional selection. Create an array ranging from 1 to 10 and find the values greater than 5.

# Create an array ranging from 1 to 10
arr = np.arange(1,11)
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) 

# Create a boolean variable and set as a condition to select elements from arr bool_arr = arr>5 
arr[bool_arr]
array([ 6, 7, 8, 9, 10])

We can also do operations on arrays.

# Create an array ranging from 1 to 10
arr = np.arange(1,11)

# Sum up arr and arr
arr + arr 
array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20])

# Exponentiate the array
arr ** 2
array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100])

1 comment:

  1. The top-down advancement of an endeavor stockroom fills in as a precise arrangement and least coordination issues. Data Analytics Course in Bangalore

    ReplyDelete