I have a list that varies in size and I would like to copy it over a numpy array. I already have a way to do but I would like to see if there is a more elegant way.
Let's say I have the following:
import numpy as np
data = np.full((10,), np.nan)
# I want to copy my list into data starting at index 2
def apply_list(my_list):
data[2:2+len(mylist)] = mylist
# Example
tmp = [1, 2, 3, 4] # can vary from 2 to 8 elements
apply_list(tmp)
After this, I expect data to look like this:
[nan, nan, 1, 2, 3, 4, nan, nan, nan, nan]
Please keep in mind that len(mylist) can range from 2 to 8.
I am marking unused places with NaN and data has been preallocated and should always be size=10, regardless of the size of my_list. For that reason, simply appending will not work.
I particularly don't like much doing 2:2+len(mylist). Is there a nicer/cleaner way of doing this?
x[2:7] = np.arange(5). Assignment to a list works the same way - except that the RHS slot does not have match in size. Array size is fixed, list size is not.