Show Sidebar Hide Sidebar

Append

How to add values to the end of a NumPy array.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Imports

This tutorial imports Plotly and Numpy.

In [1]:
import plotly.plotly as py
import plotly.graph_objs as go

import numpy as np

Append Data

Very similar in application to the core Python list method .append(), the np.append() function takes an array and some values in the form of an array and extends the length of the given array and adds the given item at the end.

In [2]:
import plotly.plotly as py
import plotly.graph_objs as go

array = np.array([1, 2, 3, 4, 5])
longer_array = np.append(array, [6, 7, 8])

trace1 = go.Scatter(
    x=array,
    y=[1 for i in array],
    mode='markers',
    marker=dict(
        size=[5 + 3*j for j in array]
    ),
    name='array'
)
trace2 = go.Scatter(
    x=longer_array,
    y=[2 for j in longer_array],
    mode='markers',
    marker=dict(
        size=[5 + 3*j for j in longer_array]
    ),
    name='longer_array'
)

py.iplot([trace1, trace2], filename='numpy-append')
Out[2]:
In [3]:
help(np.append)
Help on function append in module numpy.lib.function_base:

append(arr, values, axis=None)
    Append values to the end of an array.
    
    Parameters
    ----------
    arr : array_like
        Values are appended to a copy of this array.
    values : array_like
        These values are appended to a copy of `arr`.  It must be of the
        correct shape (the same shape as `arr`, excluding `axis`).  If
        `axis` is not specified, `values` can be any shape and will be
        flattened before use.
    axis : int, optional
        The axis along which `values` are appended.  If `axis` is not
        given, both `arr` and `values` are flattened before use.
    
    Returns
    -------
    append : ndarray
        A copy of `arr` with `values` appended to `axis`.  Note that
        `append` does not occur in-place: a new array is allocated and
        filled.  If `axis` is None, `out` is a flattened array.
    
    See Also
    --------
    insert : Insert elements into an array.
    delete : Delete elements from an array.
    
    Examples
    --------
    >>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
    array([1, 2, 3, 4, 5, 6, 7, 8, 9])
    
    When `axis` is specified, `values` must have the correct shape.
    
    >>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
    array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])
    >>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)
    Traceback (most recent call last):
    ...
    ValueError: arrays must have same number of dimensions

Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.