1

I have a numpy array like below


cf = 
[[ 0.06605101 -0.37910558]
 [ 0.01950959 -0.13871163]
 [-0.07609168  0.35762712]
 [-0.10962792  0.53259178]
 [-0.20441798  1.02187988]
 [-0.27493986  1.3927189 ]
 [-0.32651418  1.66157985]
 [ 0.1344195  -0.73359827]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [-0.01140529  0.02146107]
 [-0.14210564  0.70305015]
 [ 0.19425714 -1.04428677]
 [ 0.21070736 -1.13055805]
 [ 0.24264512 -1.29770194]
 [ 0.2739207  -1.45405194]
 [ 0.34871618 -1.84201387]
 [ 0.41549682 -2.18784216]
 [ 0.48779434 -2.56516974]
 [ 0.61753187 -3.22472257]
 [ 0.62543066 -3.29968867]
 [ 0.67363223 -3.51593344]
 [ 0.67156065 -3.50685949]
 [ 0.67066598 -3.5027474 ]
 [ 0.61698089 -3.20216463]
 [ 0.33951472 -1.80812563]
 [ 0.16105593 -0.88319653]]

But I would like to delete rows that values are [ 0. 0. ].

To do that, my code is

for idx in range(cf.shape[0]):
    if cf[idx,0] == 0 and cf[idx,1] == 0 :
        np.delete(cf,idx,0)

But cf is nothing changed. What is the problem..? Are the [ 0. 0. ] values not exactly zero?

1
  • np.delete does not act in-place. It returns a new array. Commented Nov 20, 2019 at 1:36

1 Answer 1

3

Take advantage of numpy's vectorized methods. Say your array is a:

trimmed = cf[(cf != 0).any(axis=1)]
Sign up to request clarification or add additional context in comments.

3 Comments

It worked! Can you explain about the meaning of this?
(cf != 0) returns a True/False for each element in each row of your matrix, depending on whether the element is 0 or not. If the row is [1 0], then the output is [True False]. If the row is [0 0], then the value is [False False]. .any(axis=1) allows us to check column-wise if there are any True values. It returns True if there are and False otherwise. We want to keep all rows with True because that means there is a non-zero number, and this does just that. Best, Adrian Perea
Clear! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.