Page 207 - Ai_V3.0_c11_flipbook
P. 207

5. Create an array in NumPy using np.empty()
                 The np.empty() function in NumPy is used to create a new array of specified shape and data type, without initialising
                 the elements. This means that the values in the array are not set and can be any random values that were already in the
                 memory location used for the array.

                  Program 36: To demonstrate the use of np.empty() to create an array

                     import numpy as np
                     # Create an empty array
                     arr_empty = np.empty((3, 3))  # Creating a 3x3 empty array

                     print(arr_empty)
                 Output:

                     [[5.4e-323 0.0e+000 0.0e+000]
                     [0.0e+000 6.4e-323 0.0e+000]

                     [0.0e+000 0.0e+000 3.0e-323]]
                  Program 37: To create a NumPy array by taking values from the user through np.empty()

                     import numpy as np

                     # Get the dimensions of the array from the user
                     rows = int(input("Enter the number of rows: "))
                     cols = int(input("Enter the number of columns: "))

                     # Create an empty array

                     array = np.empty((rows, cols))
                     # Get the values from the user and fill the array

                     for i in range(rows):
                         for j in range(cols):
                             value = float(input(f"Enter the value for element ({i},{j}): "))

                             array[i, j] = value

                     # Print the array
                     print("Array:")
                     print(array)

                 Output:

                     Enter the number of rows: 2
                     Enter the number of columns: 3
                     Enter the value for element (0,0): 25
                     Enter the value for element (0,1): 36

                     Enter the value for element (0,2): 25
                     Enter the value for element (1,0): 75
                     Enter the value for element (1,1): 86
                     Enter the value for element (1,2): 35

                                                                                         Python Programming     205
   202   203   204   205   206   207   208   209   210   211   212