close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about how to make a new numpy array same size as a given array and fill it with a scalar value in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

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

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

    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.

  2. make a new numpy array same size as a given array and fill it with a scalar value

    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.

Method 1

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)

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read