Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a new numpy array same size as a given array and fill it with a scalar value

I have a numpy array with some random numbers, how can I create a new array with the same size and fill it with a single value?

I have the following code:

A=np.array([[2,2],
            [2,2]])
B=np.copy(A)
B=B.fill(1)

I want to have a new array B with the same size as A but filled with 1s. However, it returns a None object. Same when using np.full.

like image 556
mengmengxyz Avatar asked Mar 13 '16 07:03

mengmengxyz


1 Answers

You can use np.full_like:

B = np.full_like(A, 1)

This will create an array with the same properties as A and will fill it with 1.

In case you want to fill it with 1 there is a also a convenience function: np.ones_like

B = np.ones_like(A)

Your example does not work because B.fill does not return anything. It works "in-place". So you fill your B but you immediatly overwrite your variable B with the None return of fill. It would work if you use it like this:

A=np.array([[2,2], [2,2]])
B=np.copy(A)
B.fill(1)
like image 101
MSeifert Avatar answered Sep 18 '22 18:09

MSeifert