返回一个用1填充的给定形状的新数组,并在NumPy中设置所需的数据类型


要返回一个给定形状和类型的用1填充的新数组,请在Python NumPy中使用**ma.one()**方法。第一个参数设置数组的形状。第二个参数是数组所需的数据类型。

order参数建议是否以行主序(C风格)或列主序(Fortran风格)方式在内存中存储多维数据。

掩码数组是标准numpy.ndarray和掩码的组合。掩码要么是nomask,表示关联数组的任何值均有效,要么是布尔值数组,用于确定关联数组的每个元素的值是否有效。

步骤

首先,导入所需的库 -

import numpy as np
import numpy.ma as ma

使用Python NumPy中的ma.one()方法返回一个给定形状和类型的用1填充的新数组。第二个参数是数组所需的数据类型 -

arr = ma.ones((5,5), dtype=int)

显示我们的数组 -

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)

示例

# Python ma.MaskedArray - Return a new array of given shape filled with ones and also set the desired data-type

import numpy as np
import numpy.ma as ma

# To return a new array of given shape and type, filled with ones, use the ma.one() method in Python Numpy
# The 1st parameter sets the shape of the array
# The 2nd parameter is the desired data-type for the array
arr = ma.ones((5,5), dtype=int)

# 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 1]
[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]

Array datatype...
int64

Array Dimensions...
2

Our Array Shape...
(5, 5)

Elements in the Array...
25

更新于: 2022年2月3日

95 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.