简体   繁体   中英

Python with numpy: How to delete an element from each row of a 2-D array according to a specific index

Say I have a 2-D numpy array A of size 20 x 10.

I also have an array of length 20, del_ind.

I want to delete an element from each row of A according to del_ind, to get a resultant array of size 20 x 9.

How can I do this?

I looked into np.delete with a specified axis = 1, but this only deletes element from the same position for each row.

Thanks for the help

You will probably have to build a new array.

Fortunately you can avoid python loops for this task, using fancy indexing:

h, w = 20, 10
A = np.arange(h*w).reshape(h, w)
del_ind = np.random.randint(0, w, size=h)
mask = np.ones((h,w), dtype=bool)
mask[range(h), del_ind] = False
A_ = A[mask].reshape(h, w-1)

Demo with a smaller dataset:

>>> h, w = 5, 4
>>> %paste
A = np.arange(h*w).reshape(h, w)
del_ind = np.random.randint(0, w, size=h)
mask = np.ones((h,w), dtype=bool)
mask[range(h), del_ind] = False
A_ = A[mask].reshape(h, w-1)

## -- End pasted text --
>>> A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])
>>> del_ind
array([2, 2, 1, 1, 0])
>>> A_
array([[ 0,  1,  3],
       [ 4,  5,  7],
       [ 8, 10, 11],
       [12, 14, 15],
       [17, 18, 19]])

Numpy isn't known for inplace edits; it's mainly intended for statically sized matrices. For that reason, I'd recommend doing this by copying the intended elements to a new array.

Assuming that it's sufficient to delete one column from every row:

def remove_indices(arr, indices):
    result = np.empty((arr.shape[0], arr.shape[1] - 1)) 

    for i, (delete_index, row) in enumerate(zip(indices, arr)):
        result[i] = np.delete(row, delete_index)

    return result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM