Home>
I want to add an element to a double list

For the following double list (window_sc: size = 600, length = 120)

window_sc =
[[0.07253604 1.22352106 1.51126732 ... -1.15038555 -1.36619525
-0.64682961]
...
[-0.47757102 -1.07191549 -1.2205016 ... 0.17392195 0.5739615
0.37965658]]

window_sc [i] [-1] --When window_sc [i] [-6]>= 0, add "0" to the beginning of each element as shown below.
Otherwise I want to insert a "1".

window_sc =
[[[0.0.07253604 1.22352106 1.51126732 ... -1.15038555 -1.36619525
-0.64682961]
...
[1.-0.47757102 -1.07191549 -1.2205016 ... 0.17392195 0.5739615
0.37965658]]

I wrote the following code, but in the first loop window_sc becomes size = 1 and I get an error.

ValueError Traceback (most recent call last)
<ipython-input-103-fd739809bccc>in<module>
      1 for i in range (len (window_sc)-1):
      2 if window_sc [i] [-1] --window_sc [i] [-6]>= 0:
---->3 window_sc [i] = np.insert (window_sc [i], 0,0)
      4 else:
      5 window_sc [i] = np.insert (window_sc [i], 0,1)
ValueError: could not broadcast input array from shape (121) into shape (120)
Corresponding source code
import numpy as np
for i in range (len (window_sc)-1):
    if window_sc [i] [-1] --window_sc [i] [-6]>= 0:
        window_sc [i] = np.insert (window_sc [i], 0,0)
    else: else:
        window_sc [i] = np.insert (window_sc [i], 0,1)
  • Answer # 1

    You can also process without using the for statement as shown below.

    import numpy as np
    a = np.array ([[1,2,3],
                  [6,5,4]])
    b = (a [:, -1] --a [:, -2]<= 0) .astype (int)
    # b = np.apply_along_axis (lambda r: 0 if r [-1] -r [-2]>= 0 else 1, 1, a) # This is fine
    print (b) # [0 1]
    c = np.insert (a, 0, b, axis = 1)
    print (c)
    # [[0 1 2 3]
    # [1 6 5 4]]

  • Answer # 2

    Since the matrix in numpy should have the same number of length x width once it is created (specification to improve calculation efficiency),
    If you try to expand one by one in a loop, it is impossible because only a part of the number of columns will be corrupted.

    So you need to insert it as an array for a 2D array.
    A simple sample is shown below for illustration.

    import numpy as np
    #Sample array
    ar = [[1,2,3], [4,5,6]]
    window_sc = np.array (ar)
    Let's create a list to add # 1, 0. This list is supposed to be created in a loop as you wrote
    append_ar = [[1,0]]
    Add # axis = 1 to index = 0.
    window_sc = np.insert (window_sc, 0, append_ar, axis = 1)

  • Answer # 3

    # 1
    np.c_ [window_sc [:, -1] --window_sc [:, -6]<= 0, window_sc]
    # 2
    np.concatenate (((window_sc [:, -1] --window_sc [:, -6]<= 0) [:, None], window_sc), axis = 1)
    # 3
    np.column_stack ((window_sc [:, -1] --window_sc [:, -6]<= 0, window_sc))
    # Four
    out = np.empty ((window_sc.shape [0], window_sc.shape [1] + 1), dtype = window_sc.dtype)
    out [:, 1:] = window_sc
    out [:, 0] = window_sc [:, -1] --window_sc [:, -6]<= 0