简体   繁体   中英

How to mask one ndarray using a another ndarray

I have an items array which has shape (n, 3) , and a counts array which has the same shape (n, 3) . How can I make every C in items to have count = 0 without resorting to loops?

items = np.array([['B', 'A', 'C'],
    ['B', 'B', 'C'],
    ['A', 'B', 'A'],
    ['C', 'C', 'C'],
    ['B', 'B', 'B']])

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

Expected output:

>>> counts
np.array([[1, 3, 0],
    [4, 2, 0],
    [2, 2, 1],
    [0, 0, 0],
    [1, 2, 1]])

What you're looking for is:

counts[items == 'C'] = 0

A more explicit way to express it is:

c_indices = np.where(items == 'C')
counts[c_indices] = 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM