3.6 NumPy 1: 1D and 2D NumPy Arrays

NumPy is our Linear Algebra or Matrix Algebra library. 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 usually convert data from a Pandas Dataframe to a NumPy array do more of the core ML part.

Converting Other Structures to NumPy Arrays

First of all, let's consider a list.

a = [1, 2, 3, 4, 5]

We can make this a NumPy array by the following function call:

numpya = 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"]])

In-built Values

If a is a numpyArray:


produces the number of elements of the numpy array,


produces a tuple with the size in each dimension


The NumPy array has a fixed size, but we can change the already existing elements of a numpy array. Let's take one called numpyArray.

numpyArray[n] = m

puts the value m into the nth index in numpyArray.

Additionally, if you input a list of values in place of the number n, you can produce a NumPy array that contains the values at those indices (plural for index).

numpyArray[1,2,3] = [a1, a2, a3]

Where a1, a2 and a3 are respectively the elements of numpyArray at the indices 1, 2 and 3.



produces a list of integers between a and b, exclusive of b.


: 1,2,3,4

2D NumPy Arrays

2D NumPy Arrays are a lot like 1D ones. It's just that they are created in the following way:


is created by:

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 discuss the useful operations using NumPy arrays provides.

Previous Section

Next Section


Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.

#.# Section Name