11_NumPy
11_NumPy
[2]: height
[4]: weight
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_12332/605548465.py in <module>
----> 1 weight / height ** 2
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'
1
[9]: np_height
[11]: np_weight
[13]: bmi
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]
[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)
[18]: x = np.linspace(10,20,50)
print (x)
3
[20]: # find retstep value
x = np.linspace(1,2,5, retstep = True)
print (x)
# retstep here is 0.25
[0. 0. 0. 0. 0.]
[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.]
[[1 1]
[1 1]]
[26]: x1
4
[26]: array([1, 0, 5, 8, 9, 8])
[[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):
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:
5
itemsize: 4 bytes
nbytes: 240 bytes
In general, we expect that nbytes is equal to itemsize times size.
[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
[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
[41]: x3
[[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]: 6
[43]: x3[1,2,3]
[43]: 6
7
4.1 One-dimensional subarrays
[44]: x = np.arange(10)
x
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
8
[53]: x2[1:,0::2]
[54]: x2[1:,0::3]
[56]: x2[1:,1:3]
[57]: x2[:,1:3]
9
[61]: array([[15, 7, 6, 5],
[ 2, 12, 6, 0],
[ 4, 4, 6, 5]])
[63]: x3
[[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]]])
[65]: x3[1,0:2,0::2]
[[1 0 6]
[9 3 7]]
[[1 0 6]
[9 3 7]]
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
[15 2 4]
[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
[[1 2 3]
[4 5 6]
[7 8 9]]
11
[74]: grid = np.arange(1, 9).reshape((2, 4))
grid
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))
[77]: array([[1],
[2],
[3]])
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
[81]: grid.shape
[81]: (2, 3)
[1 2] [ 3 99 99 3 2 1]
[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)
[[0 1 2 3]
[4 5 6 7]]
[[ 8 9 10 11]
[12 13 14 15]]
[[ 0 1]
[ 4 5]
[ 8 9]
[12 13]]
[[ 2 3]
[ 6 7]
[10 11]
[14 15]]
[89]: np.vsplit?
[ ]:
[ ]:
14