Basics Flashcards
Import numpy
import numpy as np
ndarray vs python list
NumPy arrays are faster and more compact than Python lists. An array consumes less memory and is convenient to use. NumPy uses much less memory to store data and it provides a mechanism of specifying the data types
Ndarray
NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of non-negative integers. In NumPy dimensions are called axes.
Number of axes (dimensions)
ndarray.ndim
the number of axes (dimensions) of the array.
Dimentions size
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the number of axes, ndim.
ndarray.shape
the total number of elements of the array.
ndarray.size
the total number of elements of the array. This is equal to the product of the elements of shape.
Data type of elements
ndarray.dtype
an object describing the type of the elements in the array. One can create or specify dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples.
Size in bytes of each element of the array
ndarray.itemsize
the size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize.
Creating arr
you can create an array from a regular Python list or tuple using the array function. The type of the resulting array is deduced from the type of the elements in the sequences.
Zeros, Ones, Empty
The function zeros creates an array full of zeros, the function ones creates an array full of ones, and the function empty creates an array whose initial content is random and depends on the state of the memory. By default, the dtype of the created array is float64, but it can be specified via the key word argument dtype.
N-d array
array transforms sequences of sequences into two-dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and so on.
Aarange
NumPy provides the arange function which is analogous to the Python built-in range, but returns an array.
Prinitng array
Note reahape(row, colum)
Ariphmetic operations substract
(elementwise)
a = np.array([20, 30, 40, 50]) b = np.arange(4) b array([0, 1, 2, 3]) c = a - b c array([20, 29, 38, 47])
Ariphmetic operations square
(elementwise)
a = np.array([20, 30, 40, 50]) b = np.arange(4) b array([0, 1, 2, 3]) c = a**b c array([0, 1, 4, 9])
Example operations
Product operator * operates elementwise
product operator * operates elementwise in NumPy arrays. The matrix product can be performed using the @ operator (in python >=3.5) or the dot function or method:
Dot product matrix
modify an existing array rather than create a new one
Some operations, such as += and *=, act in place to modify an existing array rather than create a new one.
Arrays of different types
When operating with arrays of different types, the type of the resulting array corresponds to the more general or precise one (a behavior known as upcasting).
~~~
a = np.ones(3, dtype=np.int32)
b = np.linspace(0, pi, 3)
b.dtype.name
‘float64’
c = a + b
c
array([1. , 2.57079633, 4.14159265])
~~~
Nd array sum() max() min()
Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class.
a = rg.random((2, 3))
a
array([[0.82770259, 0.40919914, 0.54959369],
[0.02755911, 0.75351311, 0.53814331]])
a.sum()
3.1057109529998157
a.min()
0.027559113243068367
a.max()
0.8277025938204418
Min() max() sum() by axis
By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. by specifying the axis parameter you can apply an operation along the specified axis of an array (axis = 0 is column axis = 1 is row)
~~~
b = np.arange(12).reshape(3, 4)
b
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
»>
b.sum(axis=0) # sum of each column
array([12, 15, 18, 21])
»>
b.min(axis=1) # min of each row
array([0, 4, 8])
»>
b.cumsum(axis=1) # cumulative sum along each row
array([[ 0, 1, 3, 6],
[ 4, 9, 15, 22],
[ 8, 17, 27, 38]])
~~~
ufunc
“universal functions” (ufunc). Within NumPy, these functions operate elementwise on an array, producing an array as output.
mathematical functions such as sin, cos, and exp.
B = np.arange(3) B array([0, 1, 2]) np.exp(B) array([1. , 2.71828183, 7.3890561 ]) np.sqrt(B) array([0. , 1. , 1.41421356]) C = np.array([2., -1., 4.]) np.add(B, C) array([2., 0., 6.])
Indexing, Slicing and Iterating
One-dimensional arrays can be indexed, sliced and iterated over
Iterating 3d array
for row in b: print(row) [0 1 2 3] [10 11 12 13] [20 21 22 23] [30 31 32 33] [40 41 42 43]
Iterating 3d with flat
To iterate in 3d array through each element use flat
where b = np.array[[0,1], [2,3], [10,11]]
~~~
for element in b.flat:
print(element)
0
1
2
3
10
11
~~~
Random arr of floats
a = np.random.rand(3, 4) mxn = 3X4
Random int arr
Create a 3x4 array of random integers
with lowes element 0 and highest 9
~~~
a = np.random.randint(low=0, high=10, size=(3, 4), dtype=np.int32)
~~~
Flatten(ravel) array
Create a 3x4 array of random integers
a = np.random.randint(low=0, high=10, size=(3, 4), dtype=np.int32) b = a.ravel() returns the array, flattened print(b)
[2 7 8 5 4 7 1 6 8 1 3 8]
Traspose A
transposed = a.T # returns the array, transposed print(a) print(transposed) print(a.shape) print(a.T.shape)
[[2 7 8 5]
[4 7 1 6]
[8 1 3 8]]
[[2 4 8]
[7 7 1]
[8 1 3]
[5 6 8]]
(3,4)
(4, 3)
Reshape() vs Resize()
b = np.array(range(6), dtype=np.int32) print(b) c = b.reshape(2, 3) #reshape does not change original arr print(c) b.resize(2,3) #changes arr print(b)
[0 1 2 3 4 5] #original b
[[0 1 2]
[3 4 5]] # c
[[0 1 2] #resized b
[3 4 5]]
Stacking arrays
vstack() vs hstack()
Vertical stack
Horizontal stack
Stacked arrs
[[2 3] [0 9] [0 1] [2 3]] [[2 3 0 1] [0 9 2 3]]
Splitting arr
vsplit() hsplit()
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) #Split `a` into 3 sub-arrays result = np.vsplit(a, 3) #result will be: #[array([[1, 2, 3]]), array([[4, 5, 6]]), array([[7, 8, 9]])]
View() vs Copy()
View makes a shallow copy the data is not copied. Both the original array and the view share the same underlying data buffer. modifying the data in the view will affect the original array
Copy() creates deep copy of array
~~~
d = a.copy()
d is a
False
d.base is a # d doesn’t share anything with a
False
d[0, 0] = 9999
a
array([[ 0, 10, 10, 3],
[1234, 10, 10, 7],
[ 8, 10, 10, 11]])
~~~
Slicing is not a deep copy
Slicing creates a view, not a deep copy. When you slice a NumPy array, the resulting object is a new array that refers to the same data buffer
to do a real copy used copy() at the end
deep_copied_slice = arr[1:4].copy() #Modifying the deep copied slice... deep_copied_slice[0] = 20 print(arr) # Output [1, 10, 3, 4, 5]
Reverse 1d arr
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
You can reverse it with:
reversed_arr = np.flip(arr)
Reverse 2d arr
If you start with this array:
arr_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
You can reverse the content in all of the rows and all of the columns with:
reversed_arr = np.flip(arr_2d) print(reversed_arr) [[12 11 10 9] [ 8 7 6 5] [ 4 3 2 1]]
You can easily reverse only the rows with:
reversed_arr_rows = np.flip(arr_2d, axis=0) print(reversed_arr_rows) [[ 9 10 11 12] [ 5 6 7 8] [ 1 2 3 4]]
Or reverse only the columns with:
~~~
reversed_arr_columns = np.flip(arr_2d, axis=1)
print(reversed_arr_columns)
[[ 4 3 2 1]
[ 8 7 6 5]
[12 11 10 9]]
~~~