0

I am creating an ndarray from ragged nested sequences, like this:

import numpy as np
arr = np.array([[1,2], [3,4,5], [6,7,8,9], [10]], dtype=object)

In a next step, I want to use a "boolean mask" of the same length as arr to get certain elements.

Passing a mask of all True works:

my_mask = [True, True, True, True]
arr[my_mask]
# array([[list([1, 2]), list([3, 4, 5]), list([6, 7, 8, 9]), list([10])]],
      dtype=object)

However, other masks don't seem to work:

my_mask = [True, False, True, True]
arr[my_mask]
# array([], shape=(0, 4), dtype=object)

Why does the above result in an empty array?

UPDATE: In the example above I wrote arr[my_mask], but the error I got locally was actually obtained via arr[True, False, True, True], which should rather be arr[[True, False, True, True]], note the double brackets. Thanks to @Ivan and @user1740577. As such, this is not unexpected behavior, but rather a user mistake during indexing.

6
  • 1
    this work for me and output is : array([list([1, 2]), list([6, 7, 8, 9]), list([10])], dtype=object) Commented Aug 25, 2021 at 10:20
  • which version of numpy are you using ? I got the same output as @user1740577 Commented Aug 25, 2021 at 10:21
  • I am using numpy 1.21.2 Commented Aug 25, 2021 at 10:22
  • @S.A. are you actually calling arr[my_mask] or doing arr[True, True, True, True] directly? Commented Aug 25, 2021 at 10:23
  • 1
    about using bool to index array, i found this answer stackoverflow.com/a/58132572/10666066 Commented Aug 25, 2021 at 10:39

2 Answers 2

1

instead of using:

arr[True, False, True, True]

using this (when you want to pass mask, pass array of mask):

arr[[True, False, True, True]]
Sign up to request clarification or add additional context in comments.

Comments

1

You should call arr[my_mask] instead of arr[True, False, True, True].

The reason is that by indexing with True you are adding a dimension,

>>> arr[True]
array([[list([1, 2]), list([3, 4, 5]), list([6, 7, 8, 9]), list([10])]],
      dtype=object)

but then mask the second axis (formerly the first axis) with False i.e. returning no elements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.