17

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.

2
  • I don't think you need to do the assigning. So, just B.fill(1) would do the job. Commented Mar 13, 2016 at 7:55
  • Thank you! Your comment indeed helped me save lots of time! Commented Mar 14, 2016 at 5:14

1 Answer 1

34

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

Comments

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.