#!/usr/bin/env python # coding: utf-8 # # Module 3 # # ## Video 12: Slicing Arrays # **Python for the Energy Industry** # # ## 1D Arrays # # Arrays such as those seen in the previous video can be sliced in a similar way to lists: # In[1]: import numpy as np my_array = np.arange(10) print('my_array -',my_array) # get values between index 2 (included) and 6 (excluded) print('my_array[2:6] -',my_array[2:6]) # get values between index 4 (included) the end of the array print('my_array[4:] -',my_array[4:]) # get values between the start of the array and index 7 (excluded) print('my_array[:7] -',my_array[:7]) # Slicing with the form a:b:c, accesses indices between a and b, and indices that are multiples of c. For example: # In[2]: print('my_array[2:9:2] -',my_array[2:9:2]) # ## 2D Arrays # # ### Generating Arrays # # Numpy arrays can have any number of dimensions. Working with 2D arrays is common, and most functions for generating 1D arrays also work for multiple dimensions: # In[3]: # 4 by 4 array of zeros print(np.zeros((4,4))) # In[4]: # 6 by 3 array of ones print(np.ones((6,3))) # In[5]: # 2 by 10 array of random numbers print(np.random.rand(2,10)) # Note that the when specifying the shape of the array, the first argument is the number of rows and the second argument is columns. # # You can get the shape of an array: # In[6]: x = np.ones((6,3)) print(x.shape) # ### Slicing Arrays # # Accessing elements in 2D arrays is done by separating the indices with a comma. The element in the second row, third column of an array would be accessed with the slice [1,2]. # In[7]: a = np.random.rand(3,3) print(a) print('second row, third column:',a[1,2]) # This applies when slicing as well, so getting all columns of the second row would be: [1,:] # In[10]: a = np.random.rand(3,3) print(a) print('second row, all columns:',a[1,:]) # ### Filtering Arrays # # You can also access the values in an array that meet certain conditions: # In[11]: print(a[a > 0.5]) # In[12]: print(a[np.logical_and(a > 0.5, a < 0.8)]) # ### Exercise # # Create a 5 by 5 array of random numbers between 0 and 10. # In[ ]: