Numpy: Create an 1D, 2D, 3D arrays with random values

31 July 2020

Code

# Import library
import numpy as np


# Create 1D array: random floats
x1 = np.random.randn(3)
# Create 1D array: random integers
x2 = np.random.randint(low=0, high=10, size=3)

# Create 2D array: random floats
x3 = np.random.randn(3,4)
# Create 2D array: random integers
x4 = np.random.randint(low=0, high=10, size=(3,4))

# Create 3D array: random floats
x5 = np.random.randn(2,3,4)
# Create 3D array: random integers
x6 = np.random.randint(low=0, high=10, size=(2,3,4))




# Output
print('1D array: Random floats: \n', x1,'\n', 'Type:', type(x1), '\nShape:', x1.shape)
print('\n', '1D array: Random integers: \n', x2, '\n', 'Type:',type(x2), '\nShape:', x2.shape)
print("---")

print('\n 2D array: Random floats: \n', x3,'\n', 'Type:',type(x3), '\nShape:', x3.shape)
print('\n', '2D array: Random integers: \n', x4, '\n', 'Type:',type(x4), '\nShape:', x4.shape)
print("---")

print('\n 3D array: Random floats: \n', x5,'\n', 'Type:',type(x5), '\nShape:', x5.shape)
print('\n', '3D array: Random integers: \n', x6, '\n', 'Type:',type(x6), '\nShape:', x6.shape)

Output

1D array: Random floats: 
 [0.37562636 0.20801882 0.61969609] 
 Type: <class 'numpy.ndarray'> 
Shape: (3,)

 1D array: Random integers: 
 [4 5 0] 
 Type: <class 'numpy.ndarray'> 
Shape: (3,)
---

 2D array: Random floats: 
 [[-0.81983284  0.6537328  -0.34766904 -1.06942748]
 [-0.18205896  0.5773004   1.62018886  0.45199227]
 [ 0.73367846 -0.6050891  -0.62265112 -0.21146127]] 
 Type: <class 'numpy.ndarray'> 
Shape: (3, 4)

 2D array: Random integers: 
 [[9 7 8 3]
 [4 6 1 6]
 [6 2 6 1]] 
 Type: <class 'numpy.ndarray'> 
Shape: (3, 4)
---

 3D array: Random floats: 
 [[[ 0.28408021 -1.94375853  1.09282042  1.17403851]
  [ 1.68796879 -1.1177652   0.07895971  0.45097358]
  [-0.14280229 -1.02872285  1.01596557  0.94658191]]

 [[-0.90650086  1.5345628  -1.21761996 -0.9578847 ]
  [-1.17896895  0.18456544 -0.68081066  0.32414639]
  [-0.94402687  1.48925139  0.58531697  0.17207696]]] 
 Type: <class 'numpy.ndarray'> 
Shape: (2, 3, 4)

 3D array: Random integers: 
 [[[9 1 1 6]
  [9 4 3 2]
  [6 6 0 6]]

 [[7 1 5 3]
  [0 7 4 2]
  [4 7 8 3]]] 
 Type: <class 'numpy.ndarray'> 
Shape: (2, 3, 4)






Any errors in code above?
Please send a message.