6

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 3

7

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])
Sign up to request clarification or add additional context in comments.

5 Comments

What about Np.Zeroslike
That would create an entirely new array
@NickT, add @agconti to notify him/her.
@NickT you can use myArray = np.zeros_like(myArray), it works the same I think.
@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.
4

You can use slicing:

>>> a = np.array([[1,2],[3,4]])
>>> a[:] = 0
>>> a
array([[0, 0],
       [0, 0]])

Comments

3

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

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.

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.