Introduction to Numpy Array

Welcome to this lesson on understanding Numpy arrays! Today, we will be focusing on numerical computations with Numpy, specifically around the creation, manipulation, and operations of Numpy arrays.

Numpy, short for Numerical Python, is an essential library for performing numerical computations in Python. It has support for arrays (like lists in Python, but can store items of the same type), multidimensional arrays, matrices, and a large collection of high-level mathematical functions.

In the world of data manipulation using Python, understanding and being able to use Numpy arrays allows us to efficiently manage numerical data.

Creating a Numpy Array

The most common way to create a Numpy array is by using the numpy.array() function. You can pass any sequence-like object into this function, and it will be converted into an array. Let's convert a regular Python list into a Numpy array:

import numpy as np

# Create a Python list
py_list = [1, 2, 3, 4, 5]

# Convert list to a Numpy array
np_array = np.array(py_list)

print(np_array) # Output: [1 2 3 4 5]

Executing these lines creates a one-dimensional Numpy array np_array with the same elements as our regular Python list py_list.

We can also create two-dimensional arrays (similar to matrices). Let's convert a list of lists into a 2D Numpy array:

import numpy as np

# Create a 2D Python list
py_list_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Convert list to a Numpy array
np_array_2d = np.array(py_list_2d)

print(np_array_2d)
# Output:
# [[1 2 3]
#  [4 5 6]
#  [7 8 9]]

We now have a two-dimensional Numpy array np_array_2d, with each sub-list of py_list_2d as a row in np_array_2d.

Attributes of Numpy Arrays

Numpy arrays come equipped with several attributes for gaining more insights:

  • ndim tells us the number of dimensions of the array.
  • shape gives us the size of each dimension.
  • size tells us the total number of elements in the array.
  • dtype tells us the data type of the elements in the array.

Let's create a 2D array and use these attributes:

np_array = np.array([[1, 2, 3], [4, 5, 6]])

print("Dimensions: ", np_array.ndim) # Dimensions:  2
print("Shape: ", np_array.shape)     # Shape:  (2, 3)
print("Size: ", np_array.size)       # Size: 6
print("Data Type: ", np_array.dtype) # Data Type:  int64

After running these lines, we see that np_array is a 2D array (since ndim returns the value 2), has 2 rows and 3 columns (shape returns the tuple (2, 3)), contains 6 elements (size returns 6), and is of integer type (dtype returns 'int64').

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal