在 NumPy 中返回与给定数组具有相同形状和类型的新的数组
要返回一个与给定数组具有相同形状和类型的新的数组,请在 Python NumPy 中使用 **ma.empty_like()** 方法。它返回一个具有与原型相同形状和类型的未初始化(任意)数据的数组。
order 参数覆盖结果的内存布局。“C”表示 C 顺序,“F”表示 Fortran 顺序,“A”表示如果原型是 Fortran 连续的则为“F”,否则为“C”。“K”表示尽可能接近地匹配原型的布局。
步骤
首先,导入所需的库 -
import numpy as np import numpy.ma as ma
使用 Python NumPy 中的 numpy.array() 方法创建一个新的数组 -
arr = np.array([[77, 51, 92], [56, 31, 69], [73, 88, 51], [62, 45, 67]])
显示我们的数组 -
print("Array...
",arr)要返回一个与给定数组具有相同形状和类型的新的数组,请在 Python NumPy 中使用 ma.empty_like() 方法。参数是原型,即原型的形状和数据类型定义返回数组的这些相同属性 -
arr = ma.empty_like(arr)
显示我们的数组 -
print("
New Array...
",arr)获取数组的维度 -
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 with the same shape and type as a given array
import numpy as np
import numpy.ma as ma
# Create a new array using the numpy.array() method in Python Numpy
arr = np.array([[77, 51, 92], [56, 31, 69], [73, 88, 51], [62, 45, 67]])
# Displaying our array
print("Array...
",arr)
# To return a new array with the same shape and type as a given array, use the ma.empty_like() method in Python Numpy
# The parameter is the prototype i.e. the shape and data-type of prototype define these same attributes of the returned array
arr = ma.empty_like(arr)
# Displaying our array
print("
New Array...
",arr)
# 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... [[77 51 92] [56 31 69] [73 88 51] [62 45 67]] New Array... [[ 0 0 0] [ 0 140657801869488 140657802018864] [140657801869552 140657801869616 140657801869680] [140657801997616 140657801869744 140657801997680]] Array Dimensions... 2 Our Array Shape... (4, 3) Elements in the Array... 12
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP