Operations with Numpy Arrays I
-
Basically, Numpy arrays are more efficient than lists, because arrays allow you to perform element-wise operations.
-
In this element-wise operation, you can simply apply an operation to all the elements of the array by just referring to the name of the array.
Let's see an example of doing this and comparing the lists and arrays:
# list
l = [1, 2, 3, 4, 5]
lst = []
for i in range(len(l)):
lst.append(l[i] + 5) # adding 5 to every elements of this list
# array
arr = np.array(l)
arr5 = a + 5 # applying the same operation as list above
Here, we apply the same operation of adding 5 to each element of the list and array, but the array seems to be more efficient, which is why arrays are fast and key to solving large dataset problems.
# Squaring the elements in array above
arr ** 2
array([ 1, 4, 9, 16, 25, 36])
Array Slicing
-
Slicing in python means taking elements from a given index to another index.
-
The slicing in the array is the same as applying to the lists i.e. [Start: Stop: step].
-
But most of the time we will be using just [start: stop] and step by default set to one.
Example
import numpy as np
arr = np.array([11, 32, 56, -23, 7, -56])
print(arr[1:5]) # prints [32, 56, -23, 7]
-
Slicing the array from the given index to the end of the array.
import numpy as np
arr = np.array([11, 32, 56, -23, 7, -56])
print(arr[3:]) # prints [-23, 7, -56]
-
Slicing the array from the starting index to the given stop index.
import numpy as np
arr = np.array([11, 32, 56, -23, 7, -56])
print(arr[:4]) # prints element from 0th index to the 4th index (not included)
# [11, 32, 56, -23]
Negative Slicing
-
In the negative slicing, we use the -ve sign to refer index from the last.
Example
import numpy as np
arr = np.array([11, 32, 56, -23, 7, -56])
print(arr[-5:-2]) # prints [ 32 56 -23]
Step in arrays
-
We use step value to skip some of the elements in an array.
Example
import numpy as np
arr = np.array([11, 32, 56, -23, 7, -56])
print(arr[1:5:2]) # prints [32, -23]
print(arr[::2]) # prints [11, 56, 7]
Slicing 2-D Arrays
Example
Here, we are going to slice the first element, and in the first element slice the elements from index 1 to the last index.
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0, 1:4]) # prints [2, 3, 4]
print(arr[1, 1:4]) # prints [7, 8, 9]
In Above second array has an index of 1
Now, we are going to see an example of slicing from both the arrays and even getting the whole 2-D array.
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 4]) #[ 5 10]
print(arr[0:2, :]) #[[ 1 2 3 4 5]
[ 6 7 8 9 10]]