简体   繁体   中英

Tile and Modify a Numpy Array at the same time

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.

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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM