Lewis Fogden
Lewis Fogden

Reputation: 524

Creating fixed length numpy array from variable length lists

I have been generating variable length lists, a simplified example.

list_1 = [5] * 5
list_2 = [8] * 10

I then want to convert to np.array for manipulation. As such they need to be the same length (e.g. 1200), with the tail either populated with zeros, or truncated at the target length.

For a fixed length of 8, I considered setting up a zero array then filling the appropriate entries:

np_list_1 = np.zeros(8)
np_list_1[0:5] = list_1[0:5]
np_list_2 = np.zeros(8)
np_list_2[0:8] = list_2[0:8]     # longer lists are truncated

I've created the following function to produce these

def get_np_fixed_length(list_like, length):
    list_length = len(list_like)
    np_array = np.zeros(length)
    if list_length <= length:
        np_array[0:list_length] = list_like[:]
    else:
        np_array[:] = list_like[0:length]
    return np_array

Is there a more efficient way to do this? (I couldn't see anything in numpy documentation)

Upvotes: 0

Views: 7741

Answers (1)

Nicolas Heimann
Nicolas Heimann

Reputation: 2581

You did the job already. You may save some lines by using min function.

np_array = np.zeros(length)
l = min(length, len(list_like))
np_array[:l] = list_like[:l]

There is a bit more elegant way, by first creating an empty array, fill it up and then fill the tail with zeros.

Upvotes: 1

Related Questions