Search code examples
pythonarraysnumpyconcatenationsplice

Constructing array from elements of another array neatly


I am wondering how to do the following more cleanly and in the general case. I'm constructing the array final_array_transpose with elements from another array, imb_data (currently has length 5 but can have any length). Here's what I have for the len=5 case.

final_array_transpose = np.array([ 
        imb_data[0].copy(), 
        imb_data[1].copy(), 
        imb_data[2].copy(), 
        imb_data[3].copy(), 
        imb_data[4].copy(), 
        bin_label_str, 
        range(len(imb_data[0])), 
        bin_label_str,
        bin_label,
        bin_label],       
    dtype = object)

(Ignore everything past imb_data[4].copy())

How do I generalize this for any length of imb_data (imb_data is a 2D array)? Thanks!


Solution

  • Copy the whole array and use unpacking:

    final_array_transpose = np.array([ 
            *imb_data.copy(), 
            bin_label_str, 
            range(len(imb_data[0])), 
            bin_label_str,
            bin_label,
            bin_label],       
        dtype = object)
    

    If you want the entire array in imb_data.