Home > Article > Backend Development > How to generate multiple rows of repeated data in Python
When doing scientific calculations or simulations, I believe many friends will encounter such problems. For example, we have a one-dimensional array as shown below:
array = [1, 2, 3, 4, 5]
At this point, we want to stack it repeatedly along the y-axis. For example, here we set it 3 times, so that we can get the following array.
[[1. 2. 3. 4. 5.] [1. 2. 3. 4. 5.] [1. 2. 3. 4. 5.]]
So what should we do?
import numpy as np array = np.array([1, 2, 3, 4, 5]) # 原始数组 repeat_time = 3 # 沿着y轴堆叠的次数 array_final = np.ones([repeat_time, len(array)]) for i in range(repeat_time): array_final[i, :] = array print(array_final) """ result: [[1. 2. 3. 4. 5.] [1. 2. 3. 4. 5.] [1. 2. 3. 4. 5.]] """
Obviously, the above method is more troublesome. To simplify, we can use the np.repeat() function to implement this function.
import numpy as np array = np.array([1, 2, 3, 4, 5]) # 原始数组 repeat_time = 3 # 沿着y轴堆叠的次数 array_final = np.repeat(array.reshape(1, -1), axis=0, repeats=repeat_time) print(array_final) """ result: [[1 2 3 4 5] [1 2 3 4 5] [1 2 3 4 5]] """
For detailed usage of the np.repeat() function, please refer to this article------np.repeat() function.
Of course, for this situation, the easiest way is to use np.meshgrid() function to handle it.
import numpy as np array = np.array([1, 2, 3, 4, 5]) # 原始数组 repeat_time = 3 # 沿着y轴堆叠的次数 array_1 = array.copy()[0:repeat_time] array_final, array_final1 = np.meshgrid(array, array_1) print(array_final) """ result: [[1 2 3 4 5] [1 2 3 4 5] [1 2 3 4 5]] """
Of course, there are other methods, such as np.vstack() and np.concatenate() functions, which can achieve this operation. For these two functions, you can view the blog------np.concatenate() function and np.vstack() function.
The above is the detailed content of How to generate multiple rows of repeated data in Python. For more information, please follow other related articles on the PHP Chinese website!