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 that indicates the size of each dimension of the array. For example, if I have a 2D array with 3 rows and 4 columns, calling array.shape will give me (3, 4).
Additionally, I can use the ndim attribute to find out how many dimensions the array has. For instance, a 1D array will return 1 for ndim, while a 3D array will return 3. This is crucial for understanding how to manipulate the data effectively.
For example, when working with image data, which is typically a 3D array (height, width, color channels), knowing the shape helps me ensure that any operations I perform, like reshaping or slicing, are valid. Choosing between shape and ndim depends on what information I need: shape gives detailed dimensional sizes, while ndim provides a quick overview of dimensionality.