23

I have a long array:

x= ([2, 5, 4, 7, ...])

for which I need to set the first N elements to 0. So for N = 2, the desired output would be:

x = ([0, 0, 4, 7, ...])

Is there an easy way to do this in Python? Some numpy function?

3
  • 2
    How about x[:N] = 0, if it's actually a numpy array? Commented Jun 25, 2015 at 11:52
  • Indexing and assigning is covered pretty thoroughly in NumPy's documentation. Commented Jun 25, 2015 at 11:54
  • possible duplicate of Python/Numpy: Setting values to index ranges Commented Jun 25, 2015 at 11:55

2 Answers 2

43

Pure python:

x[:n] = [0] * n

with numpy:

y = numpy.array(x)
y[:n] = 0

also note that x[:n] = 0 does not work if x is a python list (instead of a numpy array).

It is also a bad idea to use [{some object here}] * n for anything mutable, because the list will not contain n different objects but n references to the same object:

>>> a = [[],[],[],[]]
>>> a[0:2] = [["a"]] * 2
>>> a
[['a'], ['a'], [], []]
>>> a[0].append("b")
>>> a
[['a', 'b'], ['a', 'b'], [], []]
Sign up to request clarification or add additional context in comments.

3 Comments

Note that 0 is the default start, and is therefore redundant.
I guess leaving out the first index looks better.
Well I guess it's a matter of taste. I think a[0:n] is more symmetric and "easier" to generalize to a[x:y], but it's probably "more pythonic" to use a[:n].
5

Just set them explicitly:

x[0:2] = 0

5 Comments

you will get a typeerror you can assign only lists to lists. (this is for normal lists in python, dont know about numpy)
And we are talking about numpy here. This works, I checked it in a console.
@bindingofisaac, it's part of Numpy's magic to make vector arithmetic easier.
np_reshaped[0:100] = 32001 sets the first 100 rows to 32001 but I want to set the first 100 columns to 32001, thoughts?
np_reshaped.transpose()[0:100] = 32001 or np_reshaped.T[0:100] = 32001 should switch axes

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.