Kartikeya Sharma
Kartikeya Sharma

Reputation: 1383

Numpy remove a row from a multidimesional array

I have a array like this

k = np.array([[   1. , -120.8,   39.5],
       [   0. , -120.5,   39.5],
       [   1. , -120.4,   39.5],
       [   1. , -120.3,   39.5]])

I am trying to remove the following row which is also at index 1 position.

b=np.array([   0. , -120.5,   39.5])

I have tried the traditional methods like the following:

k==b #try to get all True values at index 1 but instead got this
array([[False, False, False],
       [ True, False, False],
       [False, False, False],
       [False, False, False]])

Other thing I tried:

k[~(k[:,0]==0.) & (k[:,1]==-120.5) & (k[:,1]==39.5)]

Got the result like this:

array([], shape=(0, 3), dtype=float64)

I am really surprised why the above methods not working. By the way in the first method I am just trying to get the index so that i can use np.delete later. Also for this problem, I am assuming I don't know the index.

Upvotes: 1

Views: 66

Answers (1)

cs95
cs95

Reputation: 402463

Both k and b are floats, so equality comparisons are subject to floating point inaccuracies. Use np.isclose instead:

k[~np.isclose(k, b).all(axis=1)]
# array([[   1. , -120.8,   39.5],
#        [   1. , -120.4,   39.5],
#        [   1. , -120.3,   39.5]])

Where

np.isclose(k, b).all(axis=1)
# array([False,  True, False, False])

Tells you which row of k matches b.

Upvotes: 2

Related Questions