Q. Using the arrays created in Question 4 above, Write NumPy commands for the following:
(a) A 1-D array called zeros having 10 elements and all the elements are set to zero.
(b) A 1-D array called vowels having the elements ‘a’, ‘e’, ‘i’, ‘o’ and ‘u’.
(c) A 2-D array called ones having 2 rows and 5 columns and all the elements are set to 1 and dtype as int.
(d) Use nested Python lists to create a 2-D array called myarray1 having 3 rows and 3 columns and store the following data: 2.7, -2, -190, 3.4, 99.910.6, 0, 13
(e) A 2-D array called myarray2 using arange() having 3 rows and 5 columns with start value = 4, step size 4 and dtype as float.
a) Find the transpose of ones and myarray2.
b) Sort the array vowels in reverse.
c) Sort the array myarray1 such that it brings the lowest value of the column in the first row and so on.
Answer :
(a)
ones = np.ones((2, 5), dtype=int) myarray2 = np.arange(4, 4 + 3 * 5 * 4, 4, dtype=float).reshape(3, 5) #transpose of ones ones_transpose = ones.T # transpose of myarray2 myarray2_transpose = np.transpose(myarray2) print("Transpose of ones:") print(ones_transpose) print("\nTranspose of myarray2:") print(myarray2_transpose)
Transpose of ones, we use the .T attribute to obtain ones_transpose.
Transpose of myarray2, we can use the np.transpose() function, passing myarray2 as the argument. The resulting transpose is stored in myarray2_transpose.
In NumPy, you can obtain the transpose of an array using either the .T attribute or the np.transpose() function.
(b)
To sort the array vowels in reverse order in NumPy, you can use the np.sort() function with the [::-1] indexing
import numpy as np vowels = np.array(['a', 'e', 'i', 'o', 'u']) # Sort the vowels array in reverse order vowels_reverse_sorted = np.sort(vowels)[::-1] print(vowels_reverse_sorted)
(c)
To sort the array myarray1 in a way that brings the lowest value of each column to the first row and so on, you can use the np.sort() function with the axis parameter set to 0.
myarray1 = np.array([[2.7, -2, -19], [0, 3.4, 99.9], [10.6, 0, 13]]) # Sort the array myarray1 column-wise sorted_array = np.sort(myarray1, axis=0) print(sorted_array)
To sort myarray1 column-wise, we use the np.sort() function and set the axis parameter to 0. This indicates that the sorting should be performed along each column.
Post a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )