import numpy as np
# np is the alias for numpy
# Create a regular two dimensional array
arr_2d = [
[4, 2, 6],
[5, 1, 3],
[9, 8, 7]
]
np_arr_2d = np.array(arr_2d)
print(np_arr_2d)
type(np_arr_2d)
arr_1d = [4, False, 5, 9, True] # Mixed data types
np_arr_1d = np.array(arr_1d)
print(np_arr_1d) # All converted to same data type - True = 1, False = 0
arr_1d = [4, 'Hello', 5, 9, 'World'] # Mixed data types
np_arr_1d = np.array(arr_1d)
print(np_arr_1d) # All converted to string with quotes
# Let's create an array
arr_3d = [ # 4 x 3 x 3
[ # Row 1
[ 3, 24, 1], #
[69, 8, 10], # 3 x 3 array
[57, 21, 9] #
],[ # Row 2
[ 1, 19, 62], #
[25, 23, 28], #
[27, 96, 1] #
],[ # Row 3
[65, 24, 11], #
[32, 1, 84], #
[ 2, 43, 1] #
],[ # Row 4
[14, 81, 12], #
[19, 9, 21], #
[ 18, 8, 21] #
]
]
np_arr = np.array(arr_3d)
np_arr.shape # Shape of the array 3x3x3
np_arr.dtype # data type of elements in the array
np_arr.size # total number of elements in the array = 4 * 3 * 3 = 36
np_arr.ndim # number of dimensions in the array
# Generating a zero array
z_arr1 = np.zeros(3)
z_arr2x2 = np.zeros( (2, 2) ) # [2x2] dimension
print(z_arr1)
print('--------------- 2 x 2')
print(z_arr2x2)
# Generate an array of ones
# Read the arrays bottom up (3x4) x 2
np.ones( (2,3,4) )
# Generate a number sequence in array with an interval
np.arange( 10, 30, 2 )
# from 10 to < 30 with step size 2
# Creating n number of divisions between two given numbers - inclusive of the first and last number
np.linspace( 0, 12, 5 )
# Create 5 equidistant numbers from 0 to 12 inclusive
# mathematical operations
np.round( np.sin ((22/7) / 2) ) # sin ( pi/2 )
# Saving an array to a text file
arr_3x3 = [
[ 1, 2, 5 ],
[ 4, 3, 5 ],
[10, 14, 18]
]
np_3x3 = np.array(arr_3x3)
np.savetxt('test.csv', np_3x3)