在NumPy中返回一个具有给定形状,并填充为1的新数组


要在Python NumPy中返回一个具有给定形状和类型的、填充为1的新数组,可以使用**numpy.ones()**方法。第一个参数设置新数组的形状。

该函数返回一个具有给定形状、dtype和order的、填充为1的数组。dtype参数是数组所需的数 据类型,例如numpy.int8。默认为numpy.float64。order参数指定是否以行优先(C风格)或列优先(Fortran风格)的顺序在内存中存储多维数据。

NumPy 提供了全面的数学函数、随机数生成器、线性代数例程、傅里叶变换等等。它支持各种硬件和计算平台,并且可以很好地与分布式、GPU和稀疏数组库配合使用。

步骤

首先,导入所需的库:

import numpy as np

要在Python NumPy中返回一个具有给定形状和类型的、填充为1的新数组,可以使用numpy.ones()方法。第一个参数设置新数组的形状:

arr = np.ones((4))

显示我们的数组:

print("Array...
",arr)

获取数据类型:

print("
Array datatype...
",arr.dtype)

获取数组的维度:

print("
Array Dimensions...
",arr.ndim)

获取数组的形状:

print("
Our Array Shape...
",arr.shape)

获取数组中元素的个数:

print("
Elements in the Array...
",arr.size)

示例

import numpy as np
import numpy.ma as ma

# To return a new array of given shape and type, filled with ones, use the numpy.ones() method in Python Numpy
# The 1st parameter sets the shape of the new array
arr = np.ones((4))

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size)

输出

Array...
[1. 1. 1. 1.]

Array datatype...
float64

Array Dimensions...
1

Our Array Shape...
(4,)

Elements in the Array...
4

更新于:2022年2月10日

120 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.