Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

11_NumPy

The document provides an overview of NumPy, a library for numerical computing in Python, highlighting its advantages over standard Python lists, such as efficient storage and operations on large datasets. It covers key functionalities including array creation, attributes, indexing, slicing, and reshaping, along with examples of using functions like numpy.arange and numpy.linspace. Additionally, it demonstrates how to perform calculations on NumPy arrays, such as computing BMI from height and weight data.

Uploaded by

Dinesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

11_NumPy

The document provides an overview of NumPy, a library for numerical computing in Python, highlighting its advantages over standard Python lists, such as efficient storage and operations on large datasets. It covers key functionalities including array creation, attributes, indexing, slicing, and reshaping, along with examples of using functions like numpy.arange and numpy.linspace. Additionally, it demonstrates how to perform calculations on NumPy arrays, such as computing BMI from height and weight data.

Uploaded by

Dinesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

11_NumPy

September 20, 2021

[1]: height = [1.73, 1.68, 1.21, 1.89, 1.79]

[2]: height

[2]: [1.73, 1.68, 1.21, 1.89, 1.79]

[3]: weight = [65.4, 59.2, 63.6, 88.4, 68.7]

[4]: weight

[4]: [65.4, 59.2, 63.6, 88.4, 68.7]

[5]: weight / height ** 2

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_12332/605548465.py in <module>
----> 1 weight / height ** 2

TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'

Solution: NumPy (short for Numerical Python): Provide much more efficient storage and data
operations as the size grows. - Alternative to Python List: NumPy Array, - Calculations over entire
arrays - Easy and Fast
NumPy is an N-dimensional array type called ndarray. It describes the collection of items of the
same type. Items in the collection can be accessed using a zero-based index. The basic ndarray is
created using an array function in NumPy as follows: numpy.array.
[6]: import numpy as np

[7]: np.__version__

[7]: '1.19.5'

[8]: np_height = np.array(height)

1
[9]: np_height

[9]: array([1.73, 1.68, 1.21, 1.89, 1.79])

[10]: np_weight = np.array(weight)

[11]: np_weight

[11]: array([65.4, 59.2, 63.6, 88.4, 68.7])

[12]: bmi = np_weight / np_height ** 2

[13]: bmi

[13]: array([21.85171573, 20.97505669, 43.43965576, 24.7473475 , 21.44127836])

We’ll cover a few categories of basic array manipulations here:


• Creating arrays: From numerical ranges and predefined functions
• Attributes of arrays: Determining the size, shape, memory consumption, and data types of
arrays
• Indexing of arrays: Getting and setting the value of individual array elements
• Slicing of arrays: Getting and setting smaller subarrays within a larger array
• Reshaping of arrays: Changing the shape of a given array
• Joining and splitting of arrays: Combining multiple arrays into one, and splitting one array
into many

1 Creating Array
numpy.arange returns an ndarray object containing evenly spaced values within a given range. The
format of the function is as follows:
numpy.arange(start, stop, step, dtype)
• start : The start of an interval. If omitted, defaults to 0
• stop : The end of an interval (not including this number)
• step : Spacing between values, default is 1
• dtype : Data type of resulting ndarray. If not given, data type of input is used
[14]: x = np.arange(5)
print (x)

[0 1 2 3 4]

[15]: x = np.arange(5, dtype = float)


print (x)

[0. 1. 2. 3. 4.]

2
[16]: x = np.arange(10,20,2) # skipping 1 element
print (x)

[10 12 14 16 18]
numpy.linspace fuction is similar to arange() function. In this function, instead of step size, the
number of evenly spaced values between the interval is specified. The usage of this function is as
follows −
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
• num : The number of evenly spaced samples to be generated. Default is 50
• endpoint : True by default, hence the stop value is included in the sequence. If false, it is not
included
• retstep : If true, returns samples and step between the consecutive numbers
[17]: x = np.linspace(10,20)
print (x)

[10. 10.20408163 10.40816327 10.6122449 10.81632653 11.02040816


11.2244898 11.42857143 11.63265306 11.83673469 12.04081633 12.24489796
12.44897959 12.65306122 12.85714286 13.06122449 13.26530612 13.46938776
13.67346939 13.87755102 14.08163265 14.28571429 14.48979592 14.69387755
14.89795918 15.10204082 15.30612245 15.51020408 15.71428571 15.91836735
16.12244898 16.32653061 16.53061224 16.73469388 16.93877551 17.14285714
17.34693878 17.55102041 17.75510204 17.95918367 18.16326531 18.36734694
18.57142857 18.7755102 18.97959184 19.18367347 19.3877551 19.59183673
19.79591837 20. ]

[18]: x = np.linspace(10,20,50)
print (x)

[10. 10.20408163 10.40816327 10.6122449 10.81632653 11.02040816


11.2244898 11.42857143 11.63265306 11.83673469 12.04081633 12.24489796
12.44897959 12.65306122 12.85714286 13.06122449 13.26530612 13.46938776
13.67346939 13.87755102 14.08163265 14.28571429 14.48979592 14.69387755
14.89795918 15.10204082 15.30612245 15.51020408 15.71428571 15.91836735
16.12244898 16.32653061 16.53061224 16.73469388 16.93877551 17.14285714
17.34693878 17.55102041 17.75510204 17.95918367 18.16326531 18.36734694
18.57142857 18.7755102 18.97959184 19.18367347 19.3877551 19.59183673
19.79591837 20. ]

[19]: # endpoint set to false, default is true


x = np.linspace(10,30, 5, endpoint = False)
print (x)

[10. 14. 18. 22. 26.]

3
[20]: # find retstep value
x = np.linspace(1,2,5, retstep = True)
print (x)
# retstep here is 0.25

(array([1. , 1.25, 1.5 , 1.75, 2. ]), 0.25)


numpy.zeros returns a new array of specified size, filled with zeros.
[21]: # array of five zeros. Default dtype is float
x = np.zeros(5)
print (x)

[0. 0. 0. 0. 0.]

[22]: x = np.zeros((5), dtype = np.int)


print (x)

[0 0 0 0 0]
numpy.ones returns a new array of specified size and type, filled with ones.
[23]: # array of five ones. Default dtype is float
x = np.ones(5)
print (x)

[1. 1. 1. 1. 1.]

[24]: x = np.ones([2,2], dtype = int)


print (x)

[[1 1]
[1 1]]

2 NumPy Array Attributes


First let’s discuss some useful array attributes. We’ll start by defining three random arrays, a one-
dimensional, two-dimensional, and three-dimensional array. We’ll use NumPy’s random number
generator, which we will seed with a set value in order to ensure that the same random arrays are
generated each time this code is run:
[25]: #np.random.seed(1) # seed for reproducibility

x1 = np.random.randint(10, size=6) # One-dimensional array


x2 = np.random.randint(10, size=(3, 4)) # Two-dimensional array
x3 = np.random.randint(10, size=(3, 4, 5)) # Three-dimensional array

[26]: x1

4
[26]: array([1, 0, 5, 8, 9, 8])

[27]: x2 #3 rows, 4 columns

[27]: array([[3, 7, 6, 5],


[2, 1, 6, 0],
[4, 4, 6, 5]])

[28]: x3 #4 rows, 5 columns and 3 items

[28]: array([[[3, 0, 5, 8, 1],


[1, 9, 2, 5, 4],
[7, 8, 0, 6, 8],
[0, 8, 0, 0, 6]],

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

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

Each array has attributes ndim (the number of dimensions), shape (the size of each dimension),
and size (the total size of the array):

[29]: print("x3 ndim: ", x3.ndim)


print("x3 shape:", x3.shape)
print("x3 size: ", x3.size)

x3 ndim: 3
x3 shape: (3, 4, 5)
x3 size: 60
Another useful attribute is the dtype, the data type of the array.
[30]: print("dtype:", x3.dtype)

dtype: int32
Other attributes include itemsize, which lists the size (in bytes) of each array element, and nbytes,
which lists the total size (in bytes) of the array:

[31]: print("itemsize:", x3.itemsize, "bytes")


print("nbytes:", x3.nbytes, "bytes") # nbytes = itemsize * size

5
itemsize: 4 bytes
nbytes: 240 bytes
In general, we expect that nbytes is equal to itemsize times size.

3 Array Indexing: Accessing Single Elements


If you are familiar with Python’s standard list indexing, indexing in NumPy will feel quite familiar.
In a one-dimensional array, the ith value (counting from zero) can be accessed by specifying the
desired index in square brackets, just as with Python lists:
[32]: x1

[32]: array([1, 0, 5, 8, 9, 8])

[33]: x1[0]

[33]: 1

[34]: x1[4]

[34]: 9

To index from the end of the array, you can use negative indices:
[35]: x1[-1] # refers the last element

[35]: 8

[36]: x1[-2]

[36]: 9

Values can also be modified using any of the above index notation:
[37]: x2

[37]: array([[3, 7, 6, 5],


[2, 1, 6, 0],
[4, 4, 6, 5]])

[38]: x2[1,2] # row number 1; column number 2

[38]: 6

[39]: x2[0, 0] = 15
x2

6
[39]: array([[15, 7, 6, 5],
[ 2, 1, 6, 0],
[ 4, 4, 6, 5]])

[40]: x2[1,1] = 12
x2

[40]: array([[15, 7, 6, 5],


[ 2, 12, 6, 0],
[ 4, 4, 6, 5]])

[41]: x3

[41]: array([[[3, 0, 5, 8, 1],


[1, 9, 2, 5, 4],
[7, 8, 0, 6, 8],
[0, 8, 0, 0, 6]],

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

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

[42]: x3[0,2,3] # element no, row, column

[42]: 6

[43]: x3[1,2,3]

[43]: 6

4 Array Slicing: Accessing Subarrays


Just as we can use square brackets to access individual array elements, we can also use them to
access subarrays with the slice notation, marked by the colon (:) character. The NumPy slicing
syntax follows that of the standard Python list; to access a slice of an array x, use this:
x[start:stop:step]
If any of these are unspecified, they default to the values start=0, stop=size of dimension,
step=1. We’ll take a look at accessing sub-arrays in one dimension and in multiple dimensions.

7
4.1 One-dimensional subarrays
[44]: x = np.arange(10)
x

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

[45]: x[:5] # first five elements

[45]: array([0, 1, 2, 3, 4])

[46]: x[5:] # elements from index 5

[46]: array([5, 6, 7, 8, 9])

[47]: x[4:7] # middle sub-array

[47]: array([4, 5, 6])

[48]: x[::2] # every other element

[48]: array([0, 2, 4, 6, 8])

[49]: x[1::2] # every other element, starting at index 1

[49]: array([1, 3, 5, 7, 9])

A potentially confusing case is when the step value is negative. In this case, the defaults for start
and stop are swapped. This becomes a convenient way to reverse an array:
[50]: x[::-1] # all elements, reversed

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

[51]: x[5::-1] # reversed every other from index 5

[51]: array([5, 4, 3, 2, 1, 0])

4.2 Multi-dimensional subarrays


Multi-dimensional slices work in the same way, with multiple slices separated by commas. For
example:
[52]: x2

[52]: array([[15, 7, 6, 5],


[ 2, 12, 6, 0],
[ 4, 4, 6, 5]])

8
[53]: x2[1:,0::2]

[53]: array([[2, 6],


[4, 6]])

[54]: x2[1:,0::3]

[54]: array([[2, 0],


[4, 5]])

[55]: x2[1,:] # second row

[55]: array([ 2, 12, 6, 0])

[56]: x2[1:,1:3]

[56]: array([[12, 6],


[ 4, 6]])

[57]: x2[:,1:3]

[57]: array([[ 7, 6],


[12, 6],
[ 4, 6]])

[58]: x2[0:2, :2] # two rows, two columns

[58]: array([[15, 7],


[ 2, 12]])

[59]: x2[:3, ::2] # all rows, every other column

[59]: array([[15, 6],


[ 2, 6],
[ 4, 6]])

[60]: x2[:, 1::2]

[60]: array([[ 7, 5],


[12, 0],
[ 4, 5]])

Finally, subarray dimensions can even be reversed together:


[61]: x2

9
[61]: array([[15, 7, 6, 5],
[ 2, 12, 6, 0],
[ 4, 4, 6, 5]])

[62]: x2[::-1, ::-1] # all rows and columns reversed

[62]: array([[ 5, 6, 4, 4],


[ 0, 6, 12, 2],
[ 5, 6, 7, 15]])

[63]: x3

[63]: array([[[3, 0, 5, 8, 1],


[1, 9, 2, 5, 4],
[7, 8, 0, 6, 8],
[0, 8, 0, 0, 6]],

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

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

[64]: x3[0,0:2,:] # element no, row, column

[64]: array([[3, 0, 5, 8, 1],


[1, 9, 2, 5, 4]])

[65]: x3[1,0:2,0::2]

[65]: array([[1, 0, 6],


[9, 3, 7]])

[66]: for i in range(2):


print(x3[1,0:2,0::2])

[[1 0 6]
[9 3 7]]
[[1 0 6]
[9 3 7]]

[67]: for i in range(x3.shape[0]):


print(x3[1,0:2,0::2])

10
[[1 0 6]
[9 3 7]]
[[1 0 6]
[9 3 7]]
[[1 0 6]
[9 3 7]]

Accessing array rows and columns One commonly needed routine is accessing of single rows
or columns of an array. This can be done by combining indexing and slicing, using an empty slice
marked by a single colon (:):

[68]: x2

[68]: array([[15, 7, 6, 5],


[ 2, 12, 6, 0],
[ 4, 4, 6, 5]])

[69]: print(x2[:, 0]) # first column of x2

[15 2 4]

[70]: print(x2[0, :]) # first row of x2

[15 7 6 5]
In the case of row access, the empty slice can be omitted for a more compact syntax:
[71]: print(x2[0]) # equivalent to x2[0, :]

[15 7 6 5]

5 Reshaping of Arrays
Another useful type of operation is reshaping of arrays. The most flexible way of doing this is with
the reshape method. For example, if you want to put the numbers 1 through 9 in a 3 × 3 grid,
you can do the following:
[72]: grid = np.arange(1, 10)
grid

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

[73]: grid = np.arange(1, 10).reshape((3, 3)) #converting 1D array to 2D


print(grid)

[[1 2 3]
[4 5 6]
[7 8 9]]

11
[74]: grid = np.arange(1, 9).reshape((2, 4))
grid

[74]: array([[1, 2, 3, 4],


[5, 6, 7, 8]])

Note that for this to work, the size of the initial array must match the size of the reshaped array.
Another common reshaping pattern is the conversion of a one-dimensional array into a two-
dimensional row or column matrix. This can be done with the reshape method, or more easily
done by making use of the newaxis keyword within a slice operation:
[75]: x = np.array([1, 2, 3])
# row vector via reshape
x.reshape((1, 3))

[75]: array([[1, 2, 3]])

[76]: # row vector via newaxis


x[np.newaxis, :]

[76]: array([[1, 2, 3]])

[77]: x[:, np.newaxis] # reshaping on column

[77]: array([[1],
[2],
[3]])

6 Array Concatenation and Splitting


All of the preceding routines worked on single arrays. It’s also possible to combine multiple arrays
into one, and to conversely split a single array into multiple arrays. We’ll take a look at those
operations here.

6.1 Concatenation of arrays


Concatenation, or joining of two arrays in NumPy, is primarily accomplished using the routines
np.concatenate, np.vstack, and np.hstack. np.concatenate takes a tuple or list of arrays as
its first argument, as we can see here:
[78]: x = np.array([1, 2, 3])
y = np.array([3, 2, 1])
np.concatenate([x, y])

[78]: array([1, 2, 3, 3, 2, 1])

You can also concatenate more than two arrays at once:

12
[79]: z = np.array([99, 99, 99])
print(np.concatenate([x, y, z]))

[ 1 2 3 3 2 1 99 99 99]
It can also be used for two-dimensional arrays:
[80]: grid = np.array([[1, 2, 3],[4, 5, 6]])
grid

[80]: array([[1, 2, 3],


[4, 5, 6]])

[81]: grid.shape

[81]: (2, 3)

[82]: # concatenate along the first axis


np.concatenate([grid, grid])

[82]: array([[1, 2, 3],


[4, 5, 6],
[1, 2, 3],
[4, 5, 6]])

[83]: # concatenate along the second axis (zero-indexed)


np.concatenate([grid, grid], axis=1)

[83]: array([[1, 2, 3, 1, 2, 3],


[4, 5, 6, 4, 5, 6]])

6.2 Splitting of arrays


The opposite of concatenation is splitting, which is implemented by the functions np.split,
np.hsplit, and np.vsplit. For each of these, we can pass a list of indices giving the split points:
[84]: x = np.array([1, 2, 3, 99, 99, 3, 2, 1])
x1, x2 = np.split(x, [2])
print(x1, x2)

[1 2] [ 3 99 99 3 2 1]

[85]: x = np.array([1, 2, 3, 99, 99, 3, 2, 1])


x1, x2, x3 = np.split(x, [2, 4])
print(x1, x2, x3)

[1 2] [ 3 99] [99 3 2 1]

13
Notice that N split-points, leads to N + 1 subarrays. The related functions np.hsplit and
np.vsplit are similar: - Split an array into multiple sub-arrays vertically (row-wise). - Split
an array into multiple sub-arrays horizontally (column-wise)

[86]: grid = np.arange(16).reshape((4, 4))


grid

[86]: array([[ 0, 1, 2, 3],


[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])

[87]: upper, lower = np.vsplit(grid, [2])


print(upper)
print(lower)

[[0 1 2 3]
[4 5 6 7]]
[[ 8 9 10 11]
[12 13 14 15]]

[88]: left, right = np.hsplit(grid, [2])


print(left)
print(right)

[[ 0 1]
[ 4 5]
[ 8 9]
[12 13]]
[[ 2 3]
[ 6 7]
[10 11]
[14 15]]

[89]: np.vsplit?

[ ]:

[ ]:

14

You might also like