1

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.

2
  • Is the length of array i.e. N a multiple of n? Commented Jan 3, 2020 at 10:03
  • No, I can't divide them equally in chunks. N = 3008, while n is 125 Commented Jan 3, 2020 at 10:03

3 Answers 3

4

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]
Sign up to request clarification or add additional context in comments.

Comments

2
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

Comments

0

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)

Comments

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.