返回一个与给定NumPy数组形状和类型相同的全1数组
要返回一个与给定数组形状和类型相同的全1数组,请在Python NumPy中使用**numpy.ones_like()**方法。这里的第一个参数是数组的形状和数据类型,这些属性定义了返回数组的相同属性。
dtypes 覆盖结果的数据类型。order 覆盖结果的内存布局。“C”表示C序,“F”表示F序,“A”表示如果a是Fortran连续的则为“F”,否则为“C”。“K”表示尽可能匹配a的布局。
如果subok参数为True,则新创建的数组将使用a的子类类型,否则将是基类数组。默认为True。
步骤
首先,导入所需的库:
import numpy as np
使用Python NumPy中的numpy.array()方法创建一个新数组:
arr = np.array([[35, 56, 66], [88, 73, 98]])
显示数组:
print("Array...
",arr)获取数组的类型:
print("
Array type...
", arr.dtype)
获取数组的维度:
print("
Array Dimensions...
", arr.ndim)要返回一个与给定数组形状和类型相同的全1数组,请在Python NumPy中使用numpy.ones_like()方法。这里的第一个参数是数组的形状和数据类型,这些属性定义了返回数组的相同属性:
newArr = np.ones_like(arr)
print("
New Array..
", newArr)获取新数组的类型:
print("
New Array type...
", newArr.dtype)
获取新数组的维度:
print("
New Array Dimensions...
", newArr.ndim)示例
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("
Array type...
", arr.dtype)
# Get the dimensions of the Array
print("
Array 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("
New Array..
", newArr)
# Get the type of the new array
print("
New Array type...
", newArr.dtype)
# Get the dimensions of the new array
print("
New Array Dimensions...
", newArr.ndim)输出
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP