Docsity

Python NumPy – Easy Notes and Concepts, Summaries of Engineering

Toggle sidebar
bg1
NumPy: Datasets can come from a wide range of sources and in a wide range of formats, including
collections of documents, collections of images, collections of sound clips, collections of numerical
measurements, or nearly anything else. Despite this apparent heterogeneity, many datasets can be
represented fundamentally as arrays of numbers.
For example, images—particularly digital images—can be thought of as simply two-dimensional arrays
of numbers representing pixel brightness across the area. Sound clips can be thought of as one-
dimensional arrays of intensity versus time. Text can be converted in various ways into numerical
representations, such as binary digits representing the frequency of certain words or pairs of words. No
matter what the data is, the first step in making it analyzable will be to transform it into arrays of
numbers.
For this reason, efficient storage and manipulation of numerical arrays is absolutely fundamental to the
process of doing data science. NumPy arrays are like Python's built-in list type, but NumPy arrays
provide much more efficient storage and data operations as the arrays grow larger in size.
Fixed-Type Arrays in Python
Python offers several different options for storing data in efficient, fixed-type data buffers. The built-
in array module can be used to create dense arrays of a uniform type:
import array
L = list(range(10))
A = array.array('i', L)
A
Here, 'i' is a type code indicating the contents are integers.
Much more useful, however, is the ndarray object of the NumPy package. While Python's array object
provides efficient storage of array-based data, NumPy adds to this efficient operations on that data.
Creating Arrays from Python Lists
import numpy as np
Now we can use np.array to create arrays from Python lists:
# Integer array
np.array([1, 4, 2, 5, 3])
Remember that unlike Python lists, NumPy arrays can only contain data of the same type. If the types
do not match, NumPy will upcast them according to its type promotion rules; here, integers are upcast
to floating point:
np.array([3.14, 4, 2, 3])
pf3
pf4
pf5

Partial preview of the text

Download Python NumPy – Easy Notes and Concepts and more Summaries Engineering in PDF only on Docsity!

NumPy: Datasets can come from a wide range of sources and in a wide range of formats, including collections of documents, collections of images, collections of sound clips, collections of numerical measurements, or nearly anything else. Despite this apparent heterogeneity, many datasets can be represented fundamentally as arrays of numbers. For example, images—particularly digital images—can be thought of as simply two-dimensional arrays of numbers representing pixel brightness across the area. Sound clips can be thought of as one- dimensional arrays of intensity versus time. Text can be converted in various ways into numerical representations, such as binary digits representing the frequency of certain words or pairs of words. No matter what the data is, the first step in making it analyzable will be to transform it into arrays of numbers. For this reason, efficient storage and manipulation of numerical arrays is absolutely fundamental to the process of doing data science. NumPy arrays are like Python's built-in list type, but NumPy arrays provide much more efficient storage and data operations as the arrays grow larger in size. Fixed-Type Arrays in Python Python offers several different options for storing data in efficient, fixed-type data buffers. The built- in array module can be used to create dense arrays of a uniform type: import array L = list(range(10)) A = array.array('i', L) A Here, 'i' is a type code indicating the contents are integers. Much more useful, however, is the ndarray object of the NumPy package. While Python's array object provides efficient storage of array-based data, NumPy adds to this efficient operations on that data. Creating Arrays from Python Lists import numpy as np Now we can use np.array to create arrays from Python lists:

Integer array

np.array([1, 4, 2, 5, 3]) Remember that unlike Python lists, NumPy arrays can only contain data of the same type. If the types do not match, NumPy will upcast them according to its type promotion rules; here, integers are upcast to floating point: np.array([3.14, 4, 2, 3])

If we want to explicitly set the data type of the resulting array, we can use the dtype keyword: np.array([1, 2, 3, 4], dtype=np.float32) Finally, unlike Python lists, which are always one-dimensional sequences, NumPy arrays can be multidimensional. Here's one way of initializing a multidimensional array using a list of lists:

Nested lists result in multidimensional arrays

np.array([range(i, i + 3) for i in [2, 4, 6]]) Creating Arrays from Scratch Especially for larger arrays, it is more efficient to create arrays from scratch using routines built into NumPy. Here are several examples:

Create a length-10 integer array filled with 0s

np.zeros(10, dtype=int)

Create a 3x5 floating-point array filled with 1s

np.ones((3, 5), dtype=float)

Create a 3x5 array filled with 3.

np.full((3, 5), 3.14)

Create an array filled with a linear sequence

starting at 0, ending at 20, stepping by 2

(this is similar to the built-in range function)

np.arange(0, 20, 2)

Create an array of five values evenly spaced between 0 and 1

np.linspace(0, 1, 5)

Create a 3x3 array of uniformly distributed

pseudorandom values between 0 and 1

np.random.random((3, 3))

Create a 3x3 array of pseudorandom integers in the interval [0, 10)

x2[0, 0] = 12 x Keep in mind that, unlike Python lists, NumPy arrays have a fixed type. This means, for example, that if you attempt to insert a floating-point value into an integer array, the value will be silently truncated. x1[0] = 3.14159 # this will be truncated! x 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=, step=1. One-Dimensional Subarrays x1[:3] # first three elements x1[3:] # elements after index 3 x1[1:4] # middle subarray x1[::2] # every second element x1[1::2] # every second element, starting at index 1 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: x1[::-1] # all elements, reversed x1[4::-2] # every second element from index 4, reversed Multidimensional Subarrays Multidimensional slices work in the same way, with multiple slices separated by commas. x2[:2, :3] # first two rows & three columns x2[:3, ::2] # three rows, every second column x2[::-1, ::-1] # all rows & columns, reversed Accessing array rows and columns

One commonly needed routine is accessing 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 (:): x2[:, 0] # first column of x x2[0, :] # first row of x Reshaping of Arrays Another useful type of operation is reshaping of arrays, which can be done 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: grid = np.arange(1, 10).reshape(3, 3) print(grid) Note that for this to work, the size of the initial array must match the size of the reshaped array. A common reshaping operation is converting a one-dimensional array into a two-dimensional row or column matrix: x = np.array([1, 2, 3]) x.reshape((1, 3)) # row vector via reshape x.reshape((3, 1)) # column vector via reshape A convenient shorthand for this is to use np.newaxis in the slicing syntax: x[np.newaxis, :] # row vector via newaxis 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. x = np.array([1, 2, 3]) y = np.array([3, 2, 1]) np.concatenate([x, y])