Skip to content

Array manipulation routines

Alvaro edited this page Aug 11, 2016 · 14 revisions

Changing array shape

reshape(a, newshape)
ravel(a)
ndarray.flatten()

Transpose-like operations

ndarray.T

Joining arrays

concatenate((a1, a2, ...)


numpy.reshape

Gives a new shape to an array without changing its data.

Parameters:
x : array_like Angle to be reshaped.
Returns:
reshaped_array.

Example:

Python

>>> import numpy
>>> a = numpy.arange(6).reshape([3, 2])
>>> a
    array([[0, 1],
           [2, 3],
           [4, 5]])

Javascript with PyExtJS
> a = numpy.arange(6).reshape([3, 2]);
[[0, 1], [2, 3], [4, 5]]
> a = numpy.arange(6).reshape(3, 2);   // <----- It works without brackets also
[[0, 1], [2, 3], [4, 5]]

numpy.ravel

Return a contiguous flattened array.

Parameters:
x : array_like input array. The elements in a are read in the order specified by order, and packed as a 1-D array.
Returns:
y : array_like. If a is a matrix, y is a 1-D ndarray, otherwise y is an array of the same subtype as a. The shape of the returned array is (a.size,). Matrices are special cased for backward compatibility.

Example:

Python

>>> import numpy
>>> a = numpy.arange(6).reshape(3, 2)
>>> numpy.ravel(a)
    array([0, 1, 2, 3, 4, 5])

Javascript with PyExtJS
> a = numpy.arange(6).reshape(3, 2);
  [[0, 1], [2, 3], [4, 5]]
> numpy.ravel(a);
  [0, 1, 2, 3, 4, 5]

ndarray.flatten

Return a copy of the array collapsed into one dimension.

Parameters:
none.
Returns:
y : array_like. A copy of the input array, flattened to one dimension.

Example:

Python

>>> import numpy
>>> a = numpy.arange(6).reshape(3, 2)
>>> a.flatten()
    array([0, 1, 2, 3, 4, 5])

Javascript with PyExtJS
> a = numpy.arange(6).reshape(3, 2);
  [[0, 1], [2, 3], [4, 5]]
> a.flatten();
  [0, 1, 2, 3, 4, 5]

numpy.ndarray.T

Same as numpy.transpose().

Parameters:
none.
Returns:
y : array_like. An array with its axes permuted. A view is returned whenever possible.

Example:

Python

>>> import numpy
>>> a = numpy.arange(6).reshape(3, 2)
>>> a.T
    array([[0, 2, 4],
           [1, 3, 5]])

Javascript with PyExtJS
> a = numpy.arange(6).reshape(3, 2);
  [[0, 1], [2, 3], [4, 5]]
> a.T;
  [[0, 2, 4], [1, 3, 5]]

numpy.concatenate([a1, a2, ...])

Join a sequence of arrays along an existing axis.

Parameters:
a1, a2, ... : sequence of array_like. The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).
Returns:
res : ndarray. The concatenated array.

Example:

Python

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate([a, b])
    array([[1, 2],
           [3, 4],
           [5, 6]])

Javascript with PyExtJS
> a = np.array([[1, 2], [3, 4]]);
  [[0, 1], [3, 4]]
> b = np.array([[5, 6]]);
  [[5, 6]]
> np.concatenate([a, b]);
  [[0, 1], [3, 4],[5, 6]]