6️⃣

# 3.6 NumPy 1: 1D and 2D NumPy Arrays

NumPy will be the linear algebra library we will use. We will soon get into its functionalities - it has a lot of them - but here we are going to discuss a NumPy array. A NumPy array is used in a lot of plotting functionalities, and we'll be converting data from a Pandas Dataframe to a NumPy array when we reach more of the core ML parts.

## Converting Other Structures to NumPy Arrays

First, let's consider a list.
a = [1, 2, 3, 4, 5]

We can make this a NumPy array through the following function call:
numpy_arr = np.array(a)

When we want to convert a dataframe column to a NumPy Array, we can use the np.asanyarray function:
numpyArray = np.asanyarray(df[["col"]])

## Built-in Values

If a is a numpy array,
a.size
produces the number of elements in the numpy array and
a.shape
produces a tuple with the size of each dimension.

## Indexing/Slicing

The NumPy array has a fixed size, meaning we cannot insert or delete elements from it. However, we can still change the already existing elements of a numpy array. For instance, if we have an array called numpyArray and len(numpyArray)
numpyArray[n] = m
sets the th index to in the array.

Additionally, if you query a list of values in place of the number n, you can update the NumPy array to contains the values at those indices (plural for index).
numpyArray[1, 2, 3] = [a1, a2, a3]
After the above code is run, , , and will be the elements of numpyArray at indices 1, 2 and 3 respectively.

## arange

np.arange(a, b)
produces a list of all integers from and , excluding .
# the following code returns [1, 2, 3, 4]
np.arange(1, 5)

## 2D NumPy Arrays

2D NumPy Arrays are a lot like 1D arrays. To create an array, we can initialize an array (of size of arrays (each of size ). For instance,
can be created with the following line:
numpyArray = np.array([[1, 2, 3], [4, 5, 6]])
In essence, we create the corresponding 2D list, and then convert them to NumPy arrays.

In the next lesson, we'll some benefits of using NumPy arrays over python lists.

⚖️