NumPy: Create a three-dimension array, fill the array elements with values using unsigned integer (0 to 255)
NumPy: Random Exercise-17 with Solution
Write a NumPy program to create a three-dimension array with shape (300,400,5) and set to a variable. Fill the array elements with values using unsigned integer (0 to 255).
Sample Solution:
Python Code:
# Importing NumPy library and aliasing it as np
import numpy as np
# Setting the random seed to 32 for reproducibility
np.random.seed(32)
# Generating a 3D NumPy array 'nums' with dimensions 300x400x5
# Filling it with random integers in the range [0, 256) and data type uint8
nums = np.random.randint(low=0, high=256, size=(300, 400, 5), dtype=np.uint8)
# Printing the generated array 'nums'
print(nums)
Sample Output:
[[[215 42 224 219 43] [166 69 15 133 255] [105 95 54 37 201] ... [240 22 66 232 132] [ 13 85 53 220 170] [249 62 221 146 69]] [[ 73 79 148 132 164] [ 3 93 98 138 200] [174 34 31 208 130] ... [ 15 252 41 64 39] [188 216 223 124 27] [ 85 112 240 116 231]] [[227 50 243 20 171] [ 12 66 108 102 63] [107 54 0 0 173] ... [215 46 57 99 151] [243 199 31 28 179] [143 7 30 175 190]] ... [[214 64 64 212 62] [140 44 217 17 164] [226 146 247 53 199] ... [189 68 49 117 63] [ 14 17 109 82 92] [155 221 135 184 231]] [[132 194 160 136 102] [132 244 230 117 181] [146 245 21 164 29] ... [125 240 243 190 240] [137 41 157 117 155] [ 20 92 72 182 41]] [[120 45 198 218 190] [ 42 150 190 103 106] [164 71 220 114 59] ... [143 20 219 154 85] [219 190 170 227 246] [ 39 14 127 230 158]]]
Explanation:
In the above exercise –
np.random.seed(32): This line sets the random seed to 32, which ensures that the same sequence of random numbers is generated each time the code is run.
nums = np.random.randint(low=0, high=256, size=(300, 400, 5), dtype=np.uint8): This line generates a 3D array of random integers. The parameters are as follows:
- low=0: The lower bound (inclusive) for the random integers.
- high=256: The upper bound (exclusive) for the random integers.
- size=(300, 400, 5): The shape of the output array.
- dtype=np.uint8: The data type of the output array, which is an unsigned 8-bit integer. This means the integers can have values between 0 and 255 (inclusive).
print(nums): Finally print() function prints the generated 3D array of random unsigned 8-bit integers.
Python-Numpy Code Editor:
Previous: Write a NumPy program to get the n largest values of an array.
Next: NumPy Math Exercises Home.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/python-numpy-random-exercise-17.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics