1

Given a numpy array, a range, and a value, how can I fill the array with the value inside the range?

Is there a way that is faster than filling it in manually with a loop one by one?

Edit:

myArray = np.zeros(10)

What I want: [0, 0, 0, 0, 1, 1, 1, 0, 0, 0]

1
  • 2
    This is a little unclear. you can do array[range]=value if i understand you correctly. Otherwise post what you have and what you expect Commented Jun 26, 2019 at 13:34

2 Answers 2

3
arr = np.zeros(10)
arr[4:7] = 1
print(arr)

Output:

array([0., 0., 0., 0., 1., 1., 1., 0., 0., 0.])
Sign up to request clarification or add additional context in comments.

Comments

0

For computed ranges slices are quite useful:

ar = np.zeros(3*6).reshape((3,6))
for i in range(3):
    ar[i, slice(i+1,i+3)] = 1
print(ar)

Output:

[[0. 1. 1. 0. 0. 0.]
 [0. 0. 1. 1. 0. 0.]
 [0. 0. 0. 1. 1. 0.]]

Also, these allow specification of stride (step) values:

ar = np.zeros(2*10).reshape((2,10))
for i in range(2):
    ar[i, slice(i+1, i+8, 2)] = 2-i
print(ar)

Output:

[[0. 2. 0. 2. 0. 2. 0. 2. 0. 0.]
 [0. 0. 1. 0. 1. 0. 1. 0. 1. 0.]]

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.