[Python] How to efficiently create an array from a list?

Discussão em 'Python' iniciado por Stack, Setembro 8, 2025.

  1. Stack

    Stack Membro Participativo

    I have a list containing 2D arrays with same number of rows but different number of columns. I need to create a padded array of arrays with same shape. My current code is below but due to the for loop, the code is very inefficient for large lists. How can I create a padded array more efficiently?

    MWE:

    import numpy as np


    list_length = 552

    # Irregular shape arrays in the list
    # list_with_irregular_arrays[0].shape = (10, 40)
    # .
    # .
    # list_with_irregular_arrays[100].shape = (10, 60)
    list_with_irregular_arrays = [np.random.rand(10, np.random.randint(30, 70)) for _ in range(list_length)] # NOTE: Only to create example data

    # Create padded array
    num_rows = 10
    num_cols = max(arr.shape[1] for arr in list_with_irregular_arrays)
    padded_array = np.full((list_length, num_rows, num_cols), np.nan, dtype=np.float32)

    for i in range(list_length):
    arr = list_with_irregular_arrays
    padded_array[i, :, :arr.shape[1]] = arr

    Continue reading...

Compartilhe esta Página