How To Add Numpy Arrays ?

Table Of Contents:

  1. ‘+’  Operator
  2. np.concatenate()

(1) ‘+’ Operator

  • The  ‘+’ operator will ‘sum’ the elements of numpy array.

Example-1

a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])

a + b

Output:

array([ 7,  9, 11, 13, 15])

Example-2

a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])
c = np.array([11,12,13,14,15])

a + b + c

Output:

array([18, 21, 24, 27, 30])

(2) np.concatenate()

  • Join a sequence of arrays along an existing axis.

Syntax:

numpy.concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind")

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).
  • axis: int, optional – The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.
  • out: ndarray, optional – If provided, the destination to place the result. The shape must be correct, matching that of what concatenate would have returned if no out argument were specified.
  • dtype: str or type – If provided, the destination array will have this dtype. Cannot be provided together with out.
  • casting – {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional – Controls what kind of data casting may occur. Defaults to ‘same_kind’.

Returns:

  • res: ndarray – The concatenated array.

Example-1

a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])

np.concatenate((a,b))

Output:

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

Example-2

x = np.array([[1, 2], [3, 4]])
y = np.array([[5, 6]])
np.concatenate((x, y), axis=0)

Output:

array([[1, 2],
       [3, 4],
       [5, 6]])

Leave a Reply

Your email address will not be published. Required fields are marked *