How to create a 3 X 3 Matrix will all ones in it using NumPy

Viewed 446

I am learner , bit stuck with it Not getting how do I create below 3 X 3 matrix will all 1 ones in it

  1 , 1 , 1
  1 , 1 , 1
  1 , 1 , 1

My code :

import numpy as np
arr=np.ones(np.full(1)).reshape(3,3)
arr
4 Answers

What about this:

>>> np.ones((3,3))
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])

>>> np.ones((3,3)).dtype
dtype('float64')

if You want int

>>> np.ones((3,3), dtype='int')
array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])

if you want use reshape():

import numpy as np
arr=np.ones(9).reshape(3,3)

or directly:

import numpy as np
arr=np.ones(shape=(3,3))

or from another matrix:

import numpy as np
arr1=np.array([[1,2,3],[4,5,6],[7,8,9]])
arr2=np.ones_like(arr1)

read documentations (link)

shape: Shape of the new array, e.g., (2, 3) or 2.

if you want 1 instead of 1. set argumant dtype = int

dtype: The desired data-type for the array The default, None, means

Try this:- You need to use np.ones method

import numpy as np 
m = np.ones((3, 3), dtype=float) 
print(m) 

Try

import numpy as np
np.ones((3,3))
Related