简体   繁体   中英

how to delete rows and columns in numpy python?

I am having trouble creating a function which takes a matrix M as an input and deletes BOTH rows and columns containing the number 0 and giving an output containing the remaining numbers. Any help is much appreciated as I have my programming exam coming up soon.

By "deleting both rows and columns" this is what I mean: 在此处输入图像描述

import numpy as np

x = np.array([[1,2,3,4,5],
              [6,0,8,9,10],
              [11,12,13,14,15],
              [16,0,0,19,20]])

idxs_array = list(np.where(x==0))
idxs_array = [list(dict.fromkeys(x)) for x in idxs_array]

for axis, idxs in enumerate(idxs_array):
    sub_factor = 0
    for idx in idxs:
        x = np.delete(x,idx-sub_factor,axis)
        sub_factor += 1

print(x)
       
# x = [[ 1,  4,  5],
#      [11, 14, 15]]

1. Locate zero elements

First of all, we need to identify the location of the zero elements in the matrix, which can be done easily with np.where() .

np.where will return the row/column indices of the elements matched specific condition ( doc ).

row_idx, col_idx = np.where(arr == 0)

2. Remove corresponding rows/columns

To remove corresponding rows and columns, there is an easy way to do this, which is indexing ( doc ).

That is, you can specify the row (or column) you want to keep with True , else it shall be False .

print(np.arange(4)[[True, False, True, False]])
# array([0, 2])

3. Put two things together

Here is a minimal example.

arr = np.array([[ 1,  2,  3,  4,  5],
                [ 6,  0,  8,  9, 10],
                [11, 12, 13, 14, 15],
                [16,  0,  0, 19, 20]])
 
row_idx, col_idx = np.where(arr == 0)

rm_row_idx = set(row_idx.tolist())
rm_col_idx = set(col_idx.tolist())

row_mask = [i not in rm_row_idx for i in range(arr.shape[0])]
col_mask = [i not in rm_col_idx for i in range(arr.shape[1])]

arr = arr[row_mask, :]
arr = arr[:, col_mask]

print(arr)

# Shall be:
# array([[ 1,  4,  5],
#        [11, 14, 15]])

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