NumPy - Creating Arrays

Thomas J. Kennedy

Contents:

1 Overview

There are two main ways to initialize NumPy arrays:

  1. Directly in NumPy (e.g., setting everything to zero)
  2. Converting a Python list (or similar) structure

2 Array from Scratch

NumPy arrays can be…

3 Array from a List or Tuple

Creating an array from an existing list seems straightforward…

    python_list = [2, 4, 8, 16, 32, 64]
    np_array = np.array(python_list)
    print(np_array)

However, the resulting array will store ints. To create an array of floats… a decimal point must be included after each number.

    python_list = [2., 4., 8., 16., 32., 64.]
    np_array = np.array(python_list)
    print(np_array)

You can also be explicit by using the dtype keyword argument…

    python_list = [2, 4, 8, 16, 32, 64]
    np_array = np.array(python_list, dtype=np.double)
    print(np_array)

4 Multiple Dimensions

It is possible to create a matrix (or even a tensor) by providing a multi-level list, e.g.,

    matrix = [
        [3, 2],
        [2, 5]
    ]

    matrix = np.array(matrix, dtype=np.double)