Reputation: 53
Basically I have two numpy arrays which are the same size, lets say:
import numpy as np
a = np.array([0, 3, 1, 2, 5])
b = np.array([1, 3, 8, 7, 8])
And if I delete the 2 lowest numbers in NumPy array a but also want to delete the corresponding indexes in b -- how would I go about this?
Desired Result of print(a),print(b)
after deleting:
[3, 2, 5]
[3, 7, 8]
Upvotes: 0
Views: 1401
Reputation: 137
First you need to find the index of the minimum, and then remove that value in both lists. The following should work, where steps refers to the number of elements you want to remove.
steps = 2
for i in range(steps):
index = np.where(a == min(a))
np.delete(a, index)
np.delete(b, index)
Upvotes: 0
Reputation: 1744
You can use numpy.argsort
to get the sorted indices of a particular array (by default, in ascending order). Remove the first n
indices and then sort the indices using sorted
:
n = 2
indx = sorted(np.argsort(a)[n:])
Use indx
to mask both the arrays.
Example:
# Generate sample arrays
b = np.arange(7)
a = np.random.choice(b, size = b.size, replace = False)
# b = [0 1 2 3 4 5 6], a = [3 6 0 4 2 5 1]
# Generate indices
n = 2
indx = sorted(np.argsort(a)[n:])
# Mask
>>> b[indx]
[0 1 3 4 5]
>>> a[indx]
[3 6 4 2 5]
Hope this helps.
Upvotes: 1
Reputation: 27577
Here's a basic method that uses pop()
and enumerate()
:
a = [0, 3, 1, 2, 5]
b = [1, 3, 8, 7, 8]
count = 0
for i,v in enumerate(a): # For index, value in a...
if v == min(a) and count < 2: # If the value from that iteration is the smallest number and the amount of numbers removed so far is less than 2...
a.pop(i)
b.pop(i)
count += 1
print(a)
print(b)
Output:
[3, 2, 5]
[3, 7, 8]
Upvotes: 0
Reputation: 16327
Try numpy delete method, to delete elements by index.
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
index = [2, 3, 6]
new_a = np.delete(a, index)
Upvotes: 0