1

Suppose I have a 100x100 matrix in Python like below:

import numpy as np
A = np.linspace(0,100*100-1,100*100).reshape([100,100,])


print(A)

You can see A below:

[[0.000e+00 1.000e+00 2.000e+00 ... 9.700e+01 9.800e+01 9.900e+01]
 [1.000e+02 1.010e+02 1.020e+02 ... 1.970e+02 1.980e+02 1.990e+02]
 [2.000e+02 2.010e+02 2.020e+02 ... 2.970e+02 2.980e+02 2.990e+02]
 ...
 [9.700e+03 9.701e+03 9.702e+03 ... 9.797e+03 9.798e+03 9.799e+03]
 [9.800e+03 9.801e+03 9.802e+03 ... 9.897e+03 9.898e+03 9.899e+03]
 [9.900e+03 9.901e+03 9.902e+03 ... 9.997e+03 9.998e+03 9.999e+03]]

How do I delete a range of rows (like rows 5 - 50) in A?

2 Answers 2

2

create a mask array of the elements you want to keep and then just index the array.

Code:

import numpy as np
A = np.linspace(0,100*100-1,100*100).reshape([100,100,])
mask = np.ones(len(A), dtype=bool)
mask[5:50] = False
A = A[mask]

Shape before:

(100, 100)

Shape after:

(55, 100)
Sign up to request clarification or add additional context in comments.

Comments

1

@RoseGod's answer is probably more pythonic but I thought I'd post this anyway:

A = np.asarray([*A[:5], *A[50:]])

2 Comments

@RoseGod's answer is probably more pythonic, but above all more efficient. I measured a factor of 2 between the two methods.
Definitely! Good point

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.