0

I have two lists of numpy arrays and want to insert arrays of a list into arrays of another list:

big_list=[np.array([[1., 1., 2.], [1., 1., 1.9], [1., 1., 5.2]]),
          np.array([[1., 3., 5.1], [0., 0., 1.2], [1., 1., 1.4]])]

small_list= [np.array([[-1., -1., -5.]]),
             np.array([[-1., -1., -1.], [0., -2., -0.5]])]

I want to insert first array of small_list in first array of big_list and also second array of small_list in second array of big_list. I want to put small_list where the third column of big_list has a notable change. In first array of big_list, from second row to third row, the thrid column changes a lot (from 1.9 to 5.2). For the second array of big_list, the changes occurs after the first row (from 5.1 to 1.2). For example I want to use a threshold like 3, for the difference of the third column of a row with the next row. So, I want to have:

merged= [np.array([[1., 1., 2.], [1., 1., 1.9], [-1., -1., -5.], [1., 1., 5.2]]),
         np.array([[1., 3., 5.1], [-1., -1., -1.], [0., -2., -0.5], [0., 0., 1.2], [1., 1., 1.4]])]

At the moment, my code can only append rows of small_list at the end of big_list:

merged = [np.append(array, to_append, axis=0) for (array, to_append) in zip(big_list, small_list)]

Is there a way to insert thes rows where I want? In advance, I do appreciate any help.

2 Answers 2

1

Try this-

for i, arr in enumerate(big_list):
    diff = list(abs(np.diff(arr[:,-1])) >= 3)
    for t, threshold_state in enumerate(diff):
        if threshold_state:
            big_list[i] = np.insert(big_list[i], t+1, small_list[i], axis=0)

Output

[array([[ 1. ,  1. ,  2. ],
        [ 1. ,  1. ,  1.9],
        [-1. , -1. , -5. ],
        [ 1. ,  1. ,  5.2]]), 
array([[ 1. ,  3. ,  5.1],
        [-1. , -1. , -1. ],
        [ 0. , -2. , -0.5],
        [ 0. ,  0. ,  1.2],
        [ 1. ,  1. ,  1.4]])]
Sign up to request clarification or add additional context in comments.

Comments

1

Try this -

  • Loop through each element in big_list
  • idx calculates the first index where the absolute difference between the last column values is >3
  • Insert the corresponding small list in the array at the idx.
merged = []
for i in range(len(big_list)):
    idx = np.argwhere(np.abs(np.diff(big_list[i][:,2]))>3)[0]+1
    m = np.insert(big_list[i], idx, small_list[i], axis=0)
    merged.append(m)
    
merged

[array([[ 1. ,  1. ,  2. ],
        [ 1. ,  1. ,  1.9],
        [-1. , -1. , -5. ],
        [ 1. ,  1. ,  5.2]]),
 array([[ 1. ,  3. ,  5.1],
        [-1. , -1. , -1. ],
        [ 0. , -2. , -0.5],
        [ 0. ,  0. ,  1.2],
        [ 1. ,  1. ,  1.4]])]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.