Using numpy.delete() or any other function to delete from a list of lists/arrays

Question:

I have the following list, let’s call it R:

[(array([[1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]]),
  array([100, 101, 102])),
 (array([[10, 11, 12],
         [13, 14, 15],
         [16, 17, 18]]),
  array([103, 104, 105]))]

I want to be able to delete columns of R in a for loop, based on an index i. For example, if i = 3, the 3rd column should be deleted, which should result in the following new, say R1:

    [(array([[1, 2],
             [4, 5],
             [7, 8]]),
      array([100, 101])),
     (array([[10, 11],
             [13, 14],
             [16, 17]]),
      array([103, 104]))]

I have zero experience with handling such multi dimensional arrays, so I am unsure how to use numpy.delete(). My actual list R is pretty big, so I would appreciate if someone can suggest how to go about the loop.

Asked By: S C

||

Answers:

You can use np.delete with col==2 and axis=-1.

# if your 'list' be like below as you say in the question :
print(lst)
# [
#     array([[1, 2, 3],
#            [4, 5, 6],
#            [7, 8, 9]]), 
#     array([100, 101, 102]), 
#     array([[10, 11, 12],
#            [13, 14, 15],
#            [16, 17, 18]]),
#     array([103, 104, 105])
# ]

for idx, l in enumerate(lst):
    lst[idx] = np.delete(l, 2, axis=-1)

print(lst)

Output:

[
    array([[1, 2],
           [4, 5],
           [7, 8]]), 
    array([100, 101]), 
    array([[10, 11],
           [13, 14],
           [16, 17]]), 
    array([103, 104])
]

Creating input array like in the question:

import numpy as np

lst  = [[[1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]],
        [100, 101, 102],
        [[10, 11, 12],
         [13, 14, 15],
         [16, 17, 18]],
        [103, 104, 105]
       ]

lst = [np.array(l) for l in lst]

Update base comment, If you have a tuple of np.array in your list, you can try like below:

lst = [
    (np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), np.array([100, 101, 102])), 
    (np.array([[10, 11, 12], [13, 14, 15], [16, 17, 18]]), np.array([103, 104, 105]))
]

for idx, tpl  in enumerate(lst):
    lst[idx] = tuple(np.delete(l, 2, axis=-1) for l in tpl)
    
print(lst)

Output:

[
    (array([[1, 2],
            [4, 5],
            [7, 8]]), 
     array([100, 101])
    ), 
    (array([[10, 11],
            [13, 14],
            [16, 17]]), 
     array([103, 104]))
]
Answered By: I'mahdi