#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Numpy 2D array examples Important: numpy offers many useful functions that operate on an entire array without using a for-loop (or any loop structure). Therefore, please ** avoid using loops as far as possible! ** However, if you do need to traverse through an array and "visit" each element, you can use nested for-loops, as described in the example below. For Task-2 and Task-4, DO NOT use loop structures! Please go through all the functions we discussed in the lectures. For Task-1 and Task-3, you CAN use loop structures. @author: Ashesh Mahidadia """ import numpy as np a1 = np.array([ [-24, 10, 2.5, 5.8], [ 16, -4, 18, 7.1], [ 3.8, 5, 5.9, 3.7]]) # Let's print each element value, along with row and column indices (rows, cols) = a1.shape for i in range(rows) : for j in range(cols) : print("Row index: ", i , ", Column index: ", j, ", Value is ", a1[i,j]) # Let's create a new 2D array with 4 rows and 6 columns, of type float64 a2 = np.zeros( (4, 6), dtype=np.float64) (rows, cols) = a2.shape # Let's assign random numbers to each element # The function np.random.random() returns floats in the half-open interval [0.0, 1.0). for i in range(rows) : for j in range(cols) : a2[i,j] = np.random.random() * 100 max_val = np.max(a1) print ( max_val ) idx_max = np.argmax(a1) print ( idx_max ) (i, j) = np.unravel_index(9, (3,4)) print("i is " + str(i) + ", j is " + str(j) ) # ------------ ---------- ------------- ------------- # ------------ ---------- ------------- ------------- # ------------ ---------- ------------- -------------