The NumPy ndarray


The array is the core data structure of NumPy. The data object itself is known as an “n-dimensional array,” or ndarray for short. The ndarray is a vector. Recall that vectors enable many operations to be performed together when the code is executed, resulting in faster run-times that require less computer memory. You can create an ndarray from a Python object by passing the object to the ndarray function. You first need to load the NumPy library. By convention we’ll alias NumPy as np. It saves typing.

Create an Array

import numpy as np
data = np.array([1, 3, 17])
data * 2

The output is as follows in Jupyter Notebook.

array([ 2,  6, 34])

An ndarray is a multidimensional container for homogeneous data. Every array has a shape, which is expressed as a tuple indicating the size of each dimension and a dtype, which is an object describing the data type of the array.

If you try to create an array from elements of different data types, NumPy will try to convert all of the elements to the same data type, if it can.

data2 = np.array([2, 5.34, 'Bob'])
data2
# here is the output:
# array(['2', '5.34', 'Bob'], dtype='<U32')

Creating ndarrays

Leave a Reply