14

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.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
mengmengxyz
  • 819
  • 5
  • 10
  • 12

1 Answers1

28

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)
MSeifert
  • 145,886
  • 38
  • 333
  • 352