Manipulate data with ndarray

We’ll start by introducing the NDArray, MXNet’s primary tool for storing and transforming data. If you’ve worked with NumPy before, you’ll notice that an NDArray is, by design, similar to NumPy’s multi-dimensional array.

Get started

To get started, let’s import the ndarray package (nd is a shorter alias) from MXNet.

# If you haven't installed MXNet yet, you can uncomment the following line to
# install the latest stable release
# !pip install -U mxnet

from mxnet import nd

Next, let’s see how to create a 2D array (also called a matrix) with values from two sets of numbers: 1, 2, 3 and 4, 5, 6. This might also be referred to as a tuple of a tuple of integers.


We can also create a very simple matrix with the same shape (2 rows by 3 columns), but fill it with 1s.

x = nd.ones((2,3))

Often we’ll want to create arrays whose values are sampled randomly. For example, sampling values uniformly between -1 and 1. Here we create the same shape, but with random sampling.

y = nd.random.uniform(-1,1,(2,3))

You can also fill an array of a given shape with a given value, such as 2.0.

x = nd.full((2,3), 2.0)

As with NumPy, the dimensions of each NDArray are accessible by accessing the .shape attribute. We can also query its size, which is equal to the product of the components of the shape. In addition, .dtype tells the data type of the stored values.

(x.shape, x.size, x.dtype)


NDArray supports a large number of standard mathematical operations, such as element-wise multiplication:

x * y



And transposing a matrix to compute a proper matrix-matrix product:

[24]:, y.T)


MXNet NDArrays support slicing in all the ridiculous ways you might imagine accessing your data. Here’s an example of reading a particular element, which returns a 1D array with shape (1,).


Read the second and third columns from y.


and write to a specific element.

y[:,1:3] = 2

Multi-dimensional slicing is also supported.

y[1:2,0:2] = 4

Converting between MXNet NDArray and NumPy

Converting MXNet NDArrays to and from NumPy is easy. The converted arrays do not share memory.

a = x.asnumpy()
(type(a), a)