简体   繁体   English

重复 numpy 数组 x 次数

[英]repeat a numpy array x number of times

So lets say I have a numpy array that looks like this:假设我有一个 numpy 数组,如下所示:

a=np.array([1, 2, 3, 4])

and another variable that says the number of times I want it repeated, like 3.另一个变量表示我希望它重复的次数,比如 3。

My desired result would be: [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]我想要的结果是: [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

I know I could use a loop and np.concatenate() to achieve this, but I'm working with very large arrays, and was hoping for a more efficient way to do this because it seems to me that np.concatenate with a loop would take quite a long time if I have a large array and need it duplicated a large number of times (this would result in a lot of expensive copies).我知道我可以使用循环和np.concatenate()来实现这一点,但我正在使用非常大的 arrays,并希望有一种更有效的方法来做到这一点,因为在我看来np.concatenate与循环如果我有一个大数组并且需要将它复制很多次(这会导致大量昂贵的副本),那将需要很长时间。 Is there a more efficient way to do this?有没有更有效的方法来做到这一点?

This should clarify:这应该澄清:

import numpy as np

lst = [1, 2, 3, 4]
four_list = 4 * lst
print(four_list)

np_arr = np.array(lst)
np_multiplied_arr = 4 * np_arr
print(np_multiplied_arr)

np_four_arr = np.tile(np_arr, 4)
print(np_four_arr)

Result:结果:

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
[ 4  8 12 16]
[1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4]

Note how the code that works to repeat (or tile) a list in Python doesn't work as expected in Numpy, but there is the .tile() operation to help out.请注意,在 Python 中重复(或平铺)列表的代码在 Numpy 中无法按预期工作,但有.tile()操作可以提供帮助。

It may not be the best solution but you can do this:这可能不是最好的解决方案,但您可以这样做:

import numpy as np
# Our list
my_list = [1, 2, 3]
# How many times we want to repeat the list
times_to_repeat = 3
# Our final numpy array
my_numpy_array = np.array(my_list*times_to_repeat)

Thats what we will get:这就是我们将得到的:

array([1, 2, 3, 1, 2, 3, 1, 2, 3])

But if your input is in numpy array you can do it like that:但是,如果您的输入在numpy array中,您可以这样做:

import numpy as np
# Our list
my_list = list(np.array([1, 2, 3]))
# How many times we want to repeat the list
times_to_repeat = 3
# Our final numpy array
my_numpy_array = np.array(my_list*times_to_repeat)

The output will be the same as above, its a simple workaround output 将与上述相同,这是一个简单的解决方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM