Bibek Mishra
Bibek Mishra

Reputation: 190

Remove numpy rows which don't contain whole numbers

I have an array

a = np.array([[1, 2.0, 3],
              [1.23,2.5,3],
              [1,4.6,4.9]])

I want to check each value in the 2nd column for a whole number and keep that row if it is a whole number. I have tried this.

for i in range(0,len(a)):
    try:
        if a[i,1].is_integer()==False:
            a=np.delete(a,(i),axis=0)
    except IndexError:
        continue

Output:

array([[1. , 2. , 3. ],
       [1. , 4.6, 4.9]])

Desired output: array([[1. , 2. , 3. ]])

Reason for failure: When a row is deleted, i the row below moves up. Getting the desired output without using delete is also okay.

Upvotes: 4

Views: 141

Answers (2)

Taher A. Ghaleb
Taher A. Ghaleb

Reputation: 5240

You may do so using np.floor, as follows:

output = a[a[:, 1] == np.floor(a[:, 1])]

Or, you can do it using astype(int), as follows:

output = a[a[:, 1] == a[:, 1].astype(int)]

Hope it helps.

Upvotes: 4

Mehdi
Mehdi

Reputation: 4318

output = a[np.mod(a[:, 1], 1) == 0]

Upvotes: 4

Related Questions