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

Time:10-31

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.

CodePudding user response:

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])
]
  • Related