Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

Now I have an numpy array X with certain column names, format and length. How can I set all the values to 0 (or empty) in this array, without deleting the format/names etc.?

share|improve this question
up vote 5 down vote accepted

Use numpy.ndarray.fill:

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.fill(0)
>>> a
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
share|improve this answer
1  
What about Np.Zeroslike – agconti Jan 16 '14 at 18:57
1  
That would create an entirely new array – Nick T Jan 16 '14 at 18:58
    
@NickT, add @agconti to notify him/her. – falsetru Jan 16 '14 at 19:02
    
@NickT you can use myArray = np.zeros_like(myArray), it works the same I think. – heltonbiker Jan 16 '14 at 19:13
2  
@heltonbiker you're still creating an entirely new array then releasing the old one to get GC'd. Will use twice as much memory and probably take longer. – Nick T Jan 16 '14 at 20:05

You can use slicing:

>>> a = np.array([[1,2],[3,4]])
>>> a[:] = 0
>>> a
array([[0, 0],
       [0, 0]])
share|improve this answer

Use numpy.zeroes_like to create a new array, filled with zeroes but retaining type information from your existing array:

zeroed_X = numpy.zeroes_like(X)

If you want, you can save that type information from your structured array for future use too. It's all in the dtype:

my_dtype = X.dtype
share|improve this answer
    
Useful perhaps, but if someone wants to simply "empty" the array, it's better to .fill() it with something--you don't double the memory usage. – Nick T Jan 16 '14 at 20:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.