1

I'm looking for sort of the opposite of sum() I guess. Here we go:

x = array([
    [False, False, False, False, False],
    [ True, False, False, False, False],
    [ True,  True, False, False, False],
    [ True,  True,  True, False, False]])

x.sum(axis=1)
Out: array([0, 1, 2, 3])

So I want to go the opposite direction: from [0,1,2,3] to an array like x (I can specify the number of columns I want in x, of course, above it's 5).

The solution should ideally work for higher dimensions too, and I don't want to loop in Python of course, because the input could be longer than this example. That said, here's a solution using a loop:

s = np.array([0, 1, 2, 3])
y = np.zeros((len(s), 5), np.bool)
for row,col in enumerate(s):
    y[row,0:col] = True
5
  • Looks like you are thinking about stackoverflow.com/questions/26310346/… :) Commented Oct 11, 2014 at 4:02
  • @WarrenWeckesser: correct! I know how to get from here to there...but got a little stuck here. Commented Oct 11, 2014 at 4:05
  • 1
    In your loop solution, it looks like the input is x, and you create y, but earlier you say to want to go from [0, 1, 2, 3] to x (i.e. x is the output). Isn't the operation from [0,1,2,3] to the bigger boolean array what you want? Commented Oct 11, 2014 at 4:12
  • If so, you can do something like I did in stackoverflow.com/questions/26269893/…, but change the equality in the comparison to arange(A.max()+1) to < (as in @DSM's answer). Commented Oct 11, 2014 at 4:15
  • @WarrenWeckesser: yeah, the loop code I put in the question was a bit confusing so I updated it to hopefully make it more clear/self-contained/non-self-referential. Commented Oct 11, 2014 at 4:16

1 Answer 1

2

IIUC -- and I'm not sure that I do -- you could use arange and a broadcasting comparison:

>>> v = np.array([0,1,3,2])
>>> np.arange(5) < v[...,None]
array([[False, False, False, False, False],
       [ True, False, False, False, False],
       [ True,  True,  True, False, False],
       [ True,  True, False, False, False]], dtype=bool)

or in 2D:

>>> v = np.array([[1,2],[0,2]])
>>> np.arange(5) < v[...,None]
array([[[ True, False, False, False, False],
        [ True,  True, False, False, False]],

       [[False, False, False, False, False],
        [ True,  True, False, False, False]]], dtype=bool)
>>> ((np.arange(5) < v[...,None]).sum(2) == v).all()
True
Sign up to request clarification or add additional context in comments.

1 Comment

You sure did understand--even before I clarified my example. Thank you, I would not have thought of this solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.