2

I want to create a bumpy array from two different bumpy arrays. For example:

Say I have 2 arrays a and b.

a = np.array([1,3,4])

b = np.array([[1,5,51,52],[2,6,61,62],[3,7,71,72],[4,8,81,82],[5,9,91,92]])

I want it to loop through each indices in array a and find it in array b and then save the row of b into c. Like below:

c = np.array([[1,5,51,52],
              [3,7,71,72],
              [4,8,81,82]])

I have tried doing:

c=np.zeros(shape=(len(b),4))

for i in b:
    c[i]=a[b[i][:]]  

but get this error "arrays used as indices must be of integer (or boolean) type"

1 Answer 1

2

Approach #1

If a is sorted, we can use np.searchsorted, like so -

idx = np.searchsorted(a,b[:,0])         
idx[idx==a.size] = 0
out = b[a[idx] == b[:,0]]

Sample run -

In [160]: a
Out[160]: array([1, 3, 4])

In [161]: b
Out[161]: 
array([[ 1,  5, 51, 52],
       [ 2,  6, 61, 62],
       [ 3,  7, 71, 72],
       [ 4,  8, 81, 82],
       [ 5,  9, 91, 92]])

In [162]: out
Out[162]: 
array([[ 1,  5, 51, 52],
       [ 3,  7, 71, 72],
       [ 4,  8, 81, 82]])

If a is not sorted, we need to use sorter argument with searchsorted.


Approach #2

We can also use np.in1d -

b[np.in1d(b[:,0],a)]
Sign up to request clarification or add additional context in comments.

4 Comments

What if array b had other indices that are not part of a.
@cryptofish Add a sample for such a case into the question?
@cryptofish What to do with those rows that don't have matches in a. Should they be discarded in the output c?
yes. I only want to include the matches of a and discard there rest in c.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.