Introduction to Python for Engineers and Scientists by Sandeep Nagar

Introduction to Python for Engineers and Scientists by Sandeep Nagar

Author:Sandeep Nagar
Language: eng
Format: epub
Publisher: Apress, Berkeley, CA


6.12 Masking

Arrays can be indexed using the method of masking. Masking is a way to define the indexes as a separate object and then generate a new array from the original array using the mask as a rule. There are two ways that arrays can be masked: fancy indexing and indexing using boolean values. It is important to note that masking methods generate copies instead of views. The two methods are discussed in the following subsections.

6.12.1 Fancy Indexing

numpy offers quite unique indexing facilities. One of them is fancy indexing where an array of indexes can be used to generate an array of elements:

1 >>>a = numpy.arange(1000)**3# Generated cubes of first 1000 cubes

2 >>>i = numpy.array(numpy.arange(10)) # Generated an array of first 10 numbers starting from 0 upto 9

3 >>> i

4 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

5 >>>a[i] # those elements of array 'a' which has indices of elemental values if array 'i'

6 array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729])

7 >>>j = numpy.array(numpy.arange(0,50,10)) # j is an array of numbers from 0 to 50 with steps of 10

8 >>>j

9 array([ 0, 10, 20, 30, 40])

10 >>>a[j] # a[j] is the array of cubes indexed with array j

11 array([ 0, 1000, 8000, 27000, 64000])

12 >>>k = numpy.array( [ [ 1, 2], [ 11, 12 ] ] ) # k is a two dimensional array of indexes 1,2,11,12

13 >>>a[k] # a[k] is array made up of elements placed at indexes given by k

14 array([[ 1, 8],

15 [1331, 1728]])



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.