Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Return an array of ones with the same shape and type as a given array in Numpy
To return an array of ones with the same shape and type as a given array, use the numpy.ones_like() method in Python Numpy. The 1st parameter here is the shape and data-type of array-like that define these same attributes of the returned array.
The dtypes overrides the data type of the result. The order overrides the memory layout of the result. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible.
The subok parameter, if True, then the newly created array will use the sub-class type of a, otherwise it will be a base-class array. Defaults to True.
Steps
At first, import the required library −
import numpy as np
Create a new array using the numpy.array() method in Python Numpy −
arr = np.array([[35, 56, 66], [88, 73, 98]])
Display the array −
print("Array...
",arr)
Get the type of the array −
print("\nArray type...
", arr.dtype)
Get the dimensions of the Array −
print("\nArray Dimensions...
", arr.ndim)
To return an array of ones with the same shape and type as a given array, use the numpy.ones_like() method in Python Numpy. The 1st parameter here is the shape and data-type of array-like that define these same attributes of the returned array −
newArr = np.ones_like(arr)
print("\nNew Array..
", newArr)
Get the type of the new array −
print("\nNew Array type...
", newArr.dtype)
Get the dimensions of the new array −
print("\nNew Array Dimensions...
", newArr.ndim)
Example
import numpy as np
# Create a new array using the numpy.array() method in Python Numpy
arr = np.array([[35, 56, 66], [88, 73, 98]])
# Display the array
print("Array...
",arr)
# Get the type of the array
print("\nArray type...
", arr.dtype)
# Get the dimensions of the Array
print("\nArray Dimensions...
", arr.ndim)
# To return an array of ones with the same shape and type as a given array, use the numpy.ones_like() method in Python Numpy
# The 1st parameter here is the shape and data-type of array-like that define these same attributes of the returned array.
newArr = np.ones_like(arr)
print("\nNew Array..
", newArr)
# Get the type of the new array
print("\nNew Array type...
", newArr.dtype)
# Get the dimensions of the new array
print("\nNew Array Dimensions...
", newArr.ndim)
Output
Array... [[35 56 66] [88 73 98]] Array type... int64 Array Dimensions... 2 New Array.. [[1 1 1] [1 1 1]] New Array type... int64 New Array Dimensions... 2
