user3092887
user3092887

Reputation: 501

Empty an existing NumPy array

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.?

Upvotes: 5

Views: 2116

Answers (3)

falsetru
falsetru

Reputation: 369394

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])

Upvotes: 7

eskaev
eskaev

Reputation: 1128

You can use slicing:

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

Upvotes: 4

Rohan Singh
Rohan Singh

Reputation: 21535

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

Upvotes: 3

Related Questions