hedebyhedge
hedebyhedge

Reputation: 455

Slicing two numpy arrays by Boolean of the first

Let's say I have two numpy arrays, of the same length.

a = array([1, 0, 1, 1, 0, 1])

b = array([0, 1, 1, 1, 0, 0])

I can slice a so that I only get values of 1. So

a_slice = array([1, 1, 1, 1]).

How would I similarly slice b based on the positions where a = 1?

I would need

b_slice = array([0, 1, 1, 0]).

Upvotes: 0

Views: 52

Answers (3)

Paul Panzer
Paul Panzer

Reputation: 53079

You can cast a to dtype bool

b[a.astype(bool)]
# array([0, 1, 1, 0])

Upvotes: 1

Vaishali
Vaishali

Reputation: 38415

You can use np.where

mask = np.where(a == 1)

a_slice = a[mask]

You get

array([1, 1, 1, 1])


b_slice = b[mask]

You get

array([0, 1, 1, 0])

Upvotes: 0

Neil
Neil

Reputation: 14323

You can slice be where a == 1 inside your first array. By using a == 1.

import numpy as np

a = np.array([1, 0, 1, 1, 0, 1])
b = np.array([0, 1, 1, 1, 0, 0])

_slice = b[a == 1]
print(_slice)

You can get all of the ones by using a[a == 1], but that seems far less useful.

Upvotes: 1

Related Questions