import numpy as np
a=np.array([[5.24,3.28,6.99],[3.24,5.82,2.39],[2.54,3.39,6.39]])
print("Elements of array is: \n",a)
Elements of array is:
[[5.24 3.28 6.99]
[3.24 5.82 2.39]
[2.54 3.39 6.39]]
#sum of all elements of the array
print("Sum of elements of array is: ",np.sum(a))
Sum of elements of array is: 39.28
#sum of elements of a column
print("Sum of elements of of each column of the array is:
",np.sum(a,axis=0))
Sum of elements of of each column of the array is: [11.02 12.49
15.77]
#sum of elements of a row
print("Sum of elements of of each row of the array is:
",np.sum(a,axis=1))
Sum of elements of of each row of the array is: [15.51 11.45 12.32]
a[a==5.32]=15.32
print("Array elements after substituting 5.32 with 15.32 is:\n",a)
Array elements after substituting 5.32 with 15.32 is:
[[5.24 3.28 6.99]
[3.24 5.82 2.39]
[2.54 3.39 6.39]]
a[a<5.32]=15.32
print("Array elements after substituting elements lesser than 5.32
with 15.32 is:\n",a)
a=np.array([[5.24,3.28,6.99],[3.24,5.82,2.39],[2.54,3.39,6.39]])
Array elements after substituting elements lesser than 5.32 with 15.32
is:
[[15.32 15.32 6.99]
[15.32 5.82 15.32]
[15.32 15.32 6.39]]
a[a>5.32]=15.32
print(a)
a=np.array([[5.24,3.28,6.99],[3.24,5.82,2.39],[2.54,3.39,6.39]])
[[ 5.24 3.28 15.32]
[ 3.24 15.32 2.39]
[ 2.54 3.39 15.32]]
a=np.sort(a,axis=1)
print("Array sorted row wise:\n",a)
a=np.array([[5.24,3.28,6.99],[3.24,5.82,2.39],[2.54,3.39,6.39]])
Array sorted row wise:
[[3.28 5.24 6.99]
[2.39 3.24 5.82]
[2.54 3.39 6.39]]
a=np.sort(a,axis=0)
print("Array sorted column wise:\n",a)
a=np.array([[5.24,3.28,6.99],[3.24,5.82,2.39],[2.54,3.39,6.39]])
Array sorted column wise:
[[2.54 3.28 2.39]
[3.24 3.39 6.39]
[5.24 5.82 6.99]]
import numpy as np
arr=np.array([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]])
print("Array:\n",arr)
Array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
a1=arr[:,:3]
a2=arr[:,3:]
print(a1)
print("\n",a2)
[[ 0 1 2]
[ 4 5 6]
[ 8 9 10]
[12 13 14]]
[[ 3]
[ 7]
[11]
[15]]
import numpy as np
array=np.array([(2+3j),(4-1j),(2-2j),(4-3j),(3+5j)])
print("Array before sorting:",array)
sorted_array=sorted(array, key=lambda x: (x.real, x.imag))
print("Array after sorting",sorted_array)
Array before sorting: [2.+3.j 4.-1.j 2.-2.j 4.-3.j 3.+5.j]
Array after sorting [(2-2j), (2+3j), (3+5j), (4-3j), (4-1j)]
import numpy as np
dtype = [('name', 'U10'), ('height', int), ('class', float)]
data = [('John', 6, 52.5), ('Naught', 6, 48.5), ('Prince', 3, 41.1),
('Paul', 4, 43.11)]
a = np.array(data, dtype=dtype)
print("Before sorting:")
print(a)
a_sorted = np.sort(a, order='height')
print("\nAfter sorting:")
print(a_sorted)
Before sorting:
[('John', 6, 52.5 ) ('Naught', 6, 48.5 ) ('Prince', 3, 41.1 )
('Paul', 4, 43.11)]
After sorting:
[('Prince', 3, 41.1 ) ('Paul', 4, 43.11) ('John', 6, 52.5 )
('Naught', 6, 48.5 )]