Skip to content

Commit df33a3a

Browse files
authored
[Term Entry] Python NumPy - ndarray: repeat()
* Added file on repeat * minor content fixes * Minor changes ---------
1 parent cb4a663 commit df33a3a

File tree

1 file changed

+80
-0
lines changed
  • content/numpy/concepts/ndarray/terms/repeat

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
---
2+
Title: '.repeat()'
3+
Description: 'Returns the repeated elements of an array.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Arrays'
9+
- 'Data Structures'
10+
- 'Functions'
11+
- 'NumPy'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/data-science'
15+
---
16+
17+
The **`.repeat()`** method of a NumPy `ndarray` returns a new array where each element is repeated a specified number of times. It can repeat all elements in a flattened array or along a particular axis in multidimensional arrays.
18+
19+
## Syntax
20+
21+
```pseudo
22+
ndarray.repeat(repeats, axis=None)
23+
```
24+
25+
**Parameters:**
26+
27+
- `repeats`: Integer or array of integers. Specifies how many times each element should be repeated. If an array, it must match the length of the axis being repeated.
28+
- `axis` (Optional): The axis along which the values are to be repeated. If `None`, the array is flattened before repetition.
29+
30+
**Return value:**
31+
32+
A new array with repeated elements. The resulting shape depends on the `repeats` value and whether an axis is specified.
33+
34+
## Example
35+
36+
The following example creates an `ndarray`, then uses `.repeat()` to repeat the elements:
37+
38+
```py
39+
import numpy as np
40+
41+
a = np.array([1])
42+
print("a repeated:", a.repeat(3))
43+
44+
b = np.array([[1,2],[5,6]])
45+
print("b repeated:", b.repeat(2))
46+
47+
c = np.array([[1,2],[0,-1]])
48+
print("c repeated:", c.repeat(2,axis=0))
49+
```
50+
51+
The above code generates the following output:
52+
53+
```shell
54+
a repeated: [1 1 1]
55+
b repeated: [1 1 2 2 5 5 6 6]
56+
c repeated: [[ 1 2]
57+
[ 1 2]
58+
[ 0 -1]
59+
[ 0 -1]]
60+
```
61+
62+
## Codebyte Example
63+
64+
Run the following codebyte example to understand the usage of the `.repeat()` method:
65+
66+
```codebyte/python
67+
import numpy as np
68+
69+
a = np.array([-8])
70+
print("a repeated 3 times:", a.repeat(3))
71+
72+
b = np.array([[1, 2, -9], [5, 6, 0]])
73+
print("\nb repeated (flattened):", b.repeat(2))
74+
75+
c = np.array([[7, 8], [9, -3]])
76+
print("\nc repeated along axis 1:\n", c.repeat(2, axis=1))
77+
78+
d = np.array([[-1, 2], [0, -1]])
79+
print("\nd repeated 4 times (no axis):", d.repeat(4, axis=None))
80+
```

0 commit comments

Comments
 (0)