|
| 1 | +--- |
| 2 | +Title: '.shape' |
| 3 | +Description: 'Returns a tuple representing the dimensions of an ndarray.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Data Science' |
| 7 | +Tags: |
| 8 | + - 'Arrays' |
| 9 | + - 'Data Structures' |
| 10 | + - 'NumPy' |
| 11 | + - 'Tuples' |
| 12 | +CatalogContent: |
| 13 | + - 'learn-python-3' |
| 14 | + - 'paths/data-science' |
| 15 | +--- |
| 16 | + |
| 17 | +The **`.shape`** attribute of a NumPy `ndarray` returns a [tuple](https://www.codecademy.com/resources/docs/python/tuples) of integers specifying the size of the array in each dimension. It provides information about the structure and layout of the array. |
| 18 | + |
| 19 | +## Syntax |
| 20 | + |
| 21 | +```pseudo |
| 22 | +ndarray.shape |
| 23 | +``` |
| 24 | + |
| 25 | +**Parameters:** |
| 26 | + |
| 27 | +This attribute does not take any parameters. |
| 28 | + |
| 29 | +**Return value:** |
| 30 | + |
| 31 | +Returns a tuple of integers representing the size of the array along each dimension. |
| 32 | + |
| 33 | +- For a 1D array, it returns a single value (e.g., `(5,)`). |
| 34 | +- For a 2D array, it returns two values i.e. rows and columns (e.g., `(3, 4)`). |
| 35 | +- For higher dimensions, it includes one integer per axis. |
| 36 | + |
| 37 | +## Example |
| 38 | + |
| 39 | +The following example demonstrates how to use the `.shape` attribute to get the dimensions of different ndarrays: |
| 40 | + |
| 41 | +```py |
| 42 | +import numpy as np |
| 43 | + |
| 44 | +# 1D array |
| 45 | +arr_1d = np.array([1, 2, 3, 4, 5]) |
| 46 | +print(arr_1d.shape) |
| 47 | + |
| 48 | +# 2D array |
| 49 | +arr_2d = np.array([[1, 2, 3], [4, 5, 6]]) |
| 50 | +print(arr_2d.shape) |
| 51 | + |
| 52 | +# 3D array |
| 53 | +arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) |
| 54 | +print(arr_3d.shape) |
| 55 | +``` |
| 56 | + |
| 57 | +The output for the above code will be: |
| 58 | + |
| 59 | +```shell |
| 60 | +(5,) |
| 61 | +(2, 3) |
| 62 | +(2, 2, 2) |
| 63 | +``` |
| 64 | + |
| 65 | +## Codebyte Example |
| 66 | + |
| 67 | +The following codebyte example shows how to use the `.shape` attribute and modify array dimensions: |
| 68 | + |
| 69 | +```codebyte/python |
| 70 | +import numpy as np |
| 71 | +
|
| 72 | +# Create a 1D array |
| 73 | +original_array = np.array([1, 2, 3, 4, 5, 6]) |
| 74 | +print("Original shape:", original_array.shape) |
| 75 | +
|
| 76 | +# Reshape to 2D array |
| 77 | +reshaped_array = original_array.reshape(2, 3) |
| 78 | +print("Reshaped to 2D:", reshaped_array.shape) |
| 79 | +print(reshaped_array) |
| 80 | +
|
| 81 | +# Reshape to 3D array |
| 82 | +reshaped_3d = original_array.reshape(2, 3, 1) |
| 83 | +print("Reshaped to 3D:", reshaped_3d.shape) |
| 84 | +``` |
0 commit comments