如何将数组复制到特定长度的数组

2024-04-24 22:32:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一个小数组复制到特定长度的数组

示例:

var = [22,33,44,55] # ==> len(var) = 4
n = 13

我想要的新数组是:

^{pr2}$

这是我的代码:

import numpy as np
var = [22,33,44,55]
di = np.arange(13)
var_new = np.empty(13)
var_new[di] = var

我收到错误消息:

DeprecationWarning: assignment will raise an error in the future, most likely because your index result shape does not match the value array shape. You can use arr.flat[index] = values to keep the old behaviour.

但我得到了相应的变量:

var_new
array([ 22.,  33.,  44.,  55.,  22.,  33.,  44.,  55.,  22.,  33.,  44.,
    55.,  22.])

那么,如何解决这个错误呢?有其他选择吗?在


Tags: the代码import示例newindexlenvar
3条回答

使用[:]复制数组(在python中称为列表),因为它们是可变的。python的捷径就是复制副本并再添加一个 元素。在

>>> var = [22, 33, 44, 55]
>>> n = 3
>>> newlist = var[:]*n + var[:1]

给出你想要的13个元素。在

首先,您不会得到一个错误,而是一个警告:如果var_new[di]的维度与var不匹配,则var_new[di] = var将被弃用。在

其次,错误消息告诉您要做什么:使用

var_new[di].flat = var

你再也不会收到警告了,它肯定会起作用。在


如果不需要numpy,另一种简单的方法是使用^{}

^{pr2}$

有更好的方法来复制数组,例如,您可以简单地使用^{}

Return a new array with the specified shape.

If the new array is larger than the original array, then the new array is filled with repeated copies of a. [...]

>>> import numpy as np
>>> var = [22,33,44,55]
>>> n = 13
>>> np.resize(var, n)
array([22, 33, 44, 55, 22, 33, 44, 55, 22, 33, 44, 55, 22])

相关问题 更多 >