qed
qed

Reputation: 23134

Generating 1d array of shrinking ranges in numpy

I want to generate a 1D array in numpy like this:

In [181]: np.concatenate((np.arange(1, 4), np.arange(2, 4), np.arange(3, 4)))
Out[181]: array([1, 2, 3, 2, 3, 3])

On a larger scale, in pseudocode:

concatenate(1:n, 2:n, 3:n, ..., n:n)

Is there a vectorized way of doing this in numpy and/or pandas?

Upvotes: 3

Views: 135

Answers (2)

Fred Foo
Fred Foo

Reputation: 363757

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

(As pointed out by @SaulloCastro, I didn't have to use all kinds of indexing into meshgrid magic like I did in the original, accepted answer.)

Upvotes: 5

acushner
acushner

Reputation: 9946

i don't know a way to do it in a vectorized manner, but you could always generate it with something like this:

def createSweetRange(n):
    for i in xrange(1, n):
        for j in xrange(i, n):
            yield j

Upvotes: 0

Related Questions