Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
share|improve this question
    
Looks like you are thinking about stackoverflow.com/questions/26310346/… :) –  Warren Weckesser Oct 11 '14 at 4:02
    
@WarrenWeckesser: correct! I know how to get from here to there...but got a little stuck here. –  John Zwinck Oct 11 '14 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? –  Warren Weckesser Oct 11 '14 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). –  Warren Weckesser Oct 11 '14 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. –  John Zwinck Oct 11 '14 at 4:16

1 Answer 1

up vote 1 down vote accepted

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
share|improve this answer
    
You sure did understand--even before I clarified my example. Thank you, I would not have thought of this solution. –  John Zwinck Oct 11 '14 at 4:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.