简体   繁体   中英

Replacing chunks of elements in numpy array

I have an np.array like this one: x = [1,2,3,4,5,6,7,8,9,10 ... N] . I need to replace the first n chunks with a certain element, like so:

for i in np.arange(0,125):
    x[i] = x[0]
for i in np.arange(125,250):
    x[i] = x[125]
for i in np.arange(250,375):
    x[i] = x[250]

This is obviously not the way to go, but I just wrote it to this so I can show you what I need to achieve.

One way would be -

In [47]: x
Out[47]: array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21])

In [49]: n = 5

In [50]: x[::n][np.arange(len(x))//n]
Out[50]: array([10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20])

Another with np.repeat -

In [67]: np.repeat(x[::n], n)[:len(x)]
Out[67]: array([10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20])

For in-situ edit, we can reshape and assign in a broadcasted-manner, like so -

m = (len(x)-1)//n
x[:n*m].reshape(-1,n)[:] = x[:n*m:n,None]
x[n*m:] = x[n*m]
import numpy as np
x = np.arange(0,1000)
a = x[0]
b = x[125]
c = x[250]
x[0:125] = a
x[125:250] = b
x[250:375] = c

No need to write loops, you can replace bunch of values using slicing. if the splits are equal, you can loop to calculate the stat and end positions instead of hard coding

To keep flexibility in the number of slice/value pairs you can write something like:

def chunk_replace(array, slice_list, value_list):

    for s,v in zip(slice_list, value_list):
        array[s] = v
    return array

array = np.arange(1000)

slice_list = [slice(0,125), slice(125, 250), slice(250, 375)]
value_list = [array[0], array[125], array[250]]

result = chunk_replace(array, slice_list, value_list)

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