#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ENGG1811 Lecture Numpy: Creating arrays, indexing and slicing """ # Topics covered in this file # Creating arrays # Accessing and modifying elements # Dimension # Shapes # %% import numpy import numpy as np # %% Creating arrays and array elements # Creating a 1-dimensional array and print it array1 = np.array([1, 2, 3, -3, -5, -6, 8, 12]) # Print the array print('array1 is', array1) # Alternative methods to create the same array # list1 = [1, 2, 3, -3, -5, -6, 8, 12] # array1 = np.array(list1) # Viewing and modifying array elements, slicing # Same as lists array1[3] array1[7] = -10 array1[3:5] array1[:-2] array1[0:2] = [15, 4] #%% # Creating a 2-dimensional array and array2 = np.array([ [-1.2, 2, -3.1, 4.5], [ 4, -5, 3.5, 7.1], [ 2.7, 9, 1.7, 3.4]]) print('array2 is', array2) # You can access individual elements array2[0,3] # 4.5 array2[1,2] # 3.5 # Quiz: # What do you get for the following? Think about # it and type it in to verify. # array2[2,2] # array2[-2,-2] # You can do slicing too array2[0:2,0] array2[0:2,1:2] array2[:,-1] array2[:] # returns the entire numpy array # Quiz: # What is array2[2,:]? # %% # Dimension, shape array1.ndim # 1 array1.shape # (8,) array2.ndim # 2 array2.shape # (3, 4)