Elementwise Operations: Basic Operations With Scalars
Elementwise Operations: Basic Operations With Scalars
Elementwise Operations
Basic Operations
with scalars
a*b
array([ 2., 4., 6., 8.])
# Matrix multiplication
c = np.diag([1, 2, 3, 4])
print(c * c)
print("*****************")
print(c.dot(c))
[[ 1 0 0 0]
[ 0 4 0 0]
[ 0 0 9 0]
[ 0 0 0 16]]
*****************
[[ 1 0 0 0]
[ 0 4 0 0]
[ 0 0 9 0]
[ 0 0 0 16]]
Comparisions
a = np.array([1, 2, 3, 4])
b = np.array([5, 2, 2, 4])
a == b
array([False, True, False, True], dtype=bool)
a > b
#array-wise comparisions
a = np.array([1, 2, 3, 4])
b = np.array([5, 2, 2, 4])
c = np.array([1, 2, 3, 4])
np.array_equal(a, b)
False
np.array_equal(a, c)
True
Logical Operations
np.logical_and(a, b)
array([ True, False, False, False], dtype=bool)
Transcendental functions:
a = np.arange(5)
np.sin(a)
array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 ])
Shape Mismatch
a = np.arange(4) # [0,1,2,3]
error was occur as could not be broadcast together with shapes (4,) (2,)
Basic Reductions
computing sums
x = np.array([1, 2, 3, 4])
np.sum(x)
o/p: 10
Other reductions
np.all(a == a)
o/p: True
a = np.array([1, 2, 3, 2])
b = np.array([2, 2, 3, 2])
c = np.array([6, 4, 4, 5])
((a <= b) & (b <= c)).all()
o/p: True
Broadcasting
a = np.tile(np.arange(0, 40, 10), (3,1))
print(a)
print("*************")
a=a.T
print(a)
o/p: [[ 0 10 20 30]
[ 0 10 20 30]
[ 0 10 20 30]]
*************
[[ 0 0 0]
[10 10 10]
[20 20 20]
[30 30 30]]
b = np.array([0, 1, 2])
b
o/p: array([0, 1, 2])
a=[[ 0 0 0]
[10 10 10]
[20 20 20]
[30 30 30]]
b= ([ 0, 1, 2])
a+b
o/p: array ([[ 0, 1, 2],
[10, 11, 12],
[20, 21, 22],
[30, 31, 32]])
a
o/p: array([[ 0],
[10],
[20],
[30]])
> a + b
o/p: array([[ 0, 1, 2],
[10, 11, 12],
[20, 21, 22],
[30, 31, 32]])
a[0, 2, 1]
o/p: 5