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

Time:11-07

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

CodePudding user response:

Slightly change to the solution of author : user1740577

The user is expecting only integer value and not decimal values

By adding dtype=int the OP's expected output can be achieved

Code :

import numpy as np
np.ones((3,3),dtype=int)

Expected output :

array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])

CodePudding user response:

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

CodePudding user response:

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]])

CodePudding user response:

Try

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