Juan Leni
Juan Leni

Reputation: 7578

copying a list into part of a numpy array

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?

Upvotes: 1

Views: 747

Answers (1)

MSeifert
MSeifert

Reputation: 152587

I'm not aware of any numpy-function that could simplify this. However you could wrap it as function so the complexity is hidden:

def put(arr, subarr, startidx):
    arr[startidx:startidx+len(subarr)] = subarr
    return arr

or with sequential indexing (not recommended):

def put(arr, subarr, startidx):
    arr[startidx:][:len(subarr)] = subarr
    return arr

You could also pad your mylist with NaNs:

np.pad(np.array(mylist, dtype=float), 
       (2, 8-len(mylist)), 
       mode='constant', 
       constant_values=np.nan)

Upvotes: 2

Related Questions