numpy Array operators


Example

x = np.arange(4)
x
#Out:array([0, 1, 2, 3])

scalar addition is element wise

x+10
#Out: array([10, 11, 12, 13])

scalar multiplication is element wise

x*2
#Out: array([0, 2, 4, 6])

array addition is element wise

x+x
#Out: array([0, 2, 4, 6]) 

array multiplication is element wise

x*x
#Out: array([0, 1, 4, 9])

dot product (or more generally matrix multiplication) is done with a function

x.dot(x)
#Out: 14

In Python 3.5, the @ operator was added as an infix operator for matrix multiplication

x = np.diag(np.arange(4))
print(x)
'''
   Out: array([[0, 0, 0, 0],
   [0, 1, 0, 0],
   [0, 0, 2, 0],
   [0, 0, 0, 3]])
'''
print(x@x)
print(x)
'''
   Out: array([[0, 0, 0, 0],
   [0, 1, 0, 0],
   [0, 0, 4, 0],
   [0, 0, 0, 9]])
'''

Append. Returns copy with values appended. NOT in-place.

#np.append(array, values_to_append, axis=None)
x = np.array([0,1,2,3,4])
np.append(x, [5,6,7,8,9])
# Out: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x
# Out: array([0, 1, 2, 3, 4])
y = np.append(x, [5,6,7,8,9])
y
# Out: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

hstack. Horizontal stack. (column stack)
vstack. Vertical stack. (row stack)

# np.hstack(tup), np.vstack(tup)
x = np.array([0,0,0])
y = np.array([1,1,1])
z = np.array([2,2,2])
np.hstack(x,y,z)
# Out: array([0, 0, 0, 1, 1, 1, 2, 2, 2])
np.vstack(x,y,z)
# Out: array([[0, 0, 0],
#             [1, 1, 1],
#             [2, 2, 2]])