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.?
mdml
23k8 gold badges61 silver badges66 bronze badges
asked Jan 16, 2014 at 18:49
user3092887
5111 gold badge5 silver badges8 bronze badges
3 Answers 3
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])
answered Jan 16, 2014 at 18:55
falsetru
371k69 gold badges770 silver badges660 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
agconti
What about Np.Zeroslike
Nick T
That would create an entirely new array
falsetru
@NickT, add
@agconti to notify him/her.heltonbiker
@NickT you can use
myArray = np.zeros_like(myArray), it works the same I think.Nick T
@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.
You can use slicing:
>>> a = np.array([[1,2],[3,4]])
>>> a[:] = 0
>>> a
array([[0, 0],
[0, 0]])
Comments
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
answered Jan 16, 2014 at 18:58
Rohan Singh
21.7k1 gold badge43 silver badges50 bronze badges
1 Comment
Nick T
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.lang-py