Home > Backend Development > Python Tutorial > How to generate multiple rows of repeated data in Python

How to generate multiple rows of repeated data in Python

PHPz
Release: 2023-05-11 13:16:13
forward
1746 people have browsed it

Introduction

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]
Copy after login

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.]]
Copy after login

So what should we do?

General method

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.]]
"""
Copy after login

Use np.repeat function

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]]
"""
Copy after login

For detailed usage of the np.repeat() function, please refer to this article------np.repeat() function.

Use np.meshgrid 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]]
"""
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template