How to replicate array to specific length array

試著忘記壹切 提交于 2019-12-19 03:38:06

问题


I want replicate a small array to specific length array

Example:

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

The new array that I want would be:

var_new = [22,33,44,55,22,33,44,55,22,33,44,55,22]

This is my code:

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

I get error message:

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.

But I get my corresponding variable:

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

So, how to solve the error? Is there an alternative?


回答1:


There are better ways to replicate the array, for example you could simply use np.resize:

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])



回答2:


First of all, you don't get an error, but a warning, that var_new[di] = var is deprecated if var_new[di] has dimensions that do not match var.

Second, the error message tells what to do: use

var_new[di].flat = var

and you do not get a warning any more and it is guaranteed to work.


Another, easy way to do this if numpy is not needed is to just use itertools:

>>> import itertools as it
>>> var = [22, 33, 44, 55]
>>> list(it.islice(it.cycle(var), 13))
[22, 33, 44, 55, 22, 33, 44, 55, 22, 33, 44, 55, 22]



回答3:


Copy the array (called lists in python) with [:] because they are mutable. The python short cut is then just to multiply the copy and add one more element.

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

gives the 13 elements you want.




回答4:


var = [22,33,44,55]
n = 13

Repeating a list (or any other iterable) can be done without numpy, using itertools's cycle() and islice() functions

from itertools import cycle, islice
var_new = list(islice(cycle(var),0,n)


来源:https://stackoverflow.com/questions/45127810/how-to-replicate-array-to-specific-length-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!