How do you check the shape and dimensions of a NumPy array?
TechnicalMobile TesterData ScientistSoftware EngineerTo check the shape and dimensions of a NumPy array, I use the shape attribute. This attribute returns a tuple representing the size of each dimension of the array. For example, if I have an array called arr, I can simply call arr.shape to get its dimensions.
Understanding the shape is crucial because it informs how we can manipulate the data. For instance, if I have a 2D array with a shape of (3, 4), it means there are 3 rows and 4 columns. This directly impacts operations like matrix multiplication, which requires specific dimensional compatibility.
Another useful method is ndim, which tells me the number of dimensions in the array. For example, arr.ndim would return 2 for a 2D array. Choosing between shape and ndim depends on whether I need detailed size information or just the number of dimensions. Both are essential for effective data manipulation and analysis.