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.?
3 Answers
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])
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.
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
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.