Can't understand a matplotlib's example where there are both ellipsis and colons probably associated with indices

StackOverflow https://stackoverflow.com/questions/10426718

Question

I have a question about this matplotlib's example.

Here's the part that I don't understand

def update_line(num, data, line):
    line.set_data(data[...,:num])
    return line,

What does line.set_data(data[...,:num]) do?

Was it helpful?

Solution

It's a special syntax provided by numpy for slicing in multidimensional arrays. The general syntax is a[s1,s2, ... , sn], where si is the expression used for usual slicing or indexing sequences and defines desired slice in i'th dimension. For example, a[5,2:3,1::2].

The ... is the shortening for getting full slices in all dimensions. For example a[...,3] is the shortening for a[:,:,3] if a is three-dimensional.

OTHER TIPS

It is actually a numpy notation. In numpy, ... (Ellipsis) is used as a placeholder for a variable number of : slices.

From docs:

Ellipsis expand to the number of : objects needed to make a selection tuple of the same length as x.ndim. Only the first ellipsis is expanded, any others are interpreted as :.

Usage:

In : x = numpy.array(range(8)).reshape(2,2,2)

In : x
Out:
array([[[0, 1],
        [2, 3]],

       [[4, 5],
        [6, 7]]])

In : x[...,0]
Out:
array([[0, 2],
       [4, 6]])

In : x[:,:,0]
Out:
array([[0, 2],
       [4, 6]])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top