Skip to content

Commit 89a9d6d

Browse files
[Term Entry] Python NumPy - ndarray: ndim
* add .ndim docs to python numpy array (#7821) * add a new term entry for NumPy- ndarray.ndim(#7821) * Update ndim.md examples * Update ndim.md * Minor changes ---------
1 parent 7f9dd7d commit 89a9d6d

File tree

1 file changed

+75
-0
lines changed
  • content/numpy/concepts/ndarray/terms/ndim

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
---
2+
Title: 'ndim'
3+
Description: 'Returns the number of dimensions (axes) of a NumPy array.'
4+
Subjects:
5+
- 'Code Foundations'
6+
- 'Computer Science'
7+
Tags:
8+
- 'Arrays'
9+
- 'Attributes'
10+
- 'NumPy'
11+
- 'Shape'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/computer-science'
15+
---
16+
17+
The **`ndim`** attribute returns the total number of dimensions (axes) of a NumPy array. A 1D array acts like a list, a 2D array forms a matrix, and higher dimensions represent tensors which are common in data science and machine learning.
18+
19+
## Syntax
20+
21+
```pseudo
22+
ndarray.ndim
23+
```
24+
25+
**Parameters:**
26+
27+
The `ndim` attribute takes no parameters.
28+
29+
**Return value:**
30+
31+
Returns an integer representing the number of array dimensions (axes).
32+
33+
## Example: Checking Dimensions of Different Arrays
34+
35+
This example demonstrates how `ndim` behaves for 0D (scalar), 1D (list), and 2D (matrix) arrays:
36+
37+
```py
38+
import numpy as np
39+
40+
# 0D array (scalar)
41+
arr_0d = np.array(50)
42+
print("0D array:", arr_0d, "| Dimensions:", arr_0d.ndim)
43+
44+
# 1D array (list)
45+
arr_1d = np.array([1, 2, 3, 4, 5])
46+
print("1D array:", arr_1d, "| Dimensions:", arr_1d.ndim)
47+
48+
# 2D array (matrix)
49+
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
50+
print("2D array:\n", arr_2d, "\nDimensions:", arr_2d.ndim)
51+
```
52+
53+
The output of this code is:
54+
55+
```shell
56+
0D array: 50 | Dimensions: 0
57+
1D array: [1 2 3 4 5] | Dimensions: 1
58+
2D array:
59+
[[1 2 3]
60+
[4 5 6]]
61+
Dimensions: 2
62+
```
63+
64+
## Codebyte Example: Using `ndim` in a NumPy Operation
65+
66+
In this example, `ndim` is used to identify the number of dimensions in different types of image data like grayscale (2D) and color (3D):
67+
68+
```codebyte/python
69+
import numpy as np
70+
71+
arr_a = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
72+
73+
# Print the array and its number of dimensions
74+
print(f"array: {arr_a}, number of dimensions: {arr_a.ndim}")
75+
```

0 commit comments

Comments
 (0)