2

Suppose I have a Numpy array like so:

[10, 11, 12]

I want to copy it several times to form a new array, but subtract every element by 1 each time I copy, to produce:

[[10 11 12]
 [ 9 10 11]
 [ 8  9 10]
 [ 7  8  9]
 [ 6  7  8]
 [ 5  6  7]]

This is simple with a list comprehension:

import numpy as np
cycles = 6
a = np.array([10, 11, 12])

a = np.stack([a - i for i in range(cycles)])

However, I was wondering if there's a Numpy command that does this, or a more efficient way that doesn't use a list comprehension. I'm using Python 2.7.

1 Answer 1

4

One approach would be with broadcasting -

a - np.arange(6)[:,None]

Sample run -

In [94]: a
Out[94]: array([10, 11, 12])

In [95]: a - np.arange(6)[:,None]
Out[95]: 
array([[10, 11, 12],
       [ 9, 10, 11],
       [ 8,  9, 10],
       [ 7,  8,  9],
       [ 6,  7,  8],
       [ 5,  6,  7]])
Sign up to request clarification or add additional context in comments.

2 Comments

I think Approach #2 is incorrect. Make your test array a = np.array([10, 1111, 112]). Then sub1_rows(a, cycles = 10000) will return array([[ 10, 1111, 112], [ 9, 10, 1111], [ 8, 9, 10], ... ])
@AGNGazer Ah yes, that won't work for a generic input array that's not necessarily in sequence. Thanks for pointing it out! Removed that one.

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.