返回一个与给定数组具有相同形状和类型的新数组,并更改NumPy中的顺序
要返回一个与给定数组具有相同形状和类型的新数组,请在 Python NumPy 中使用 **numpy.empty_like()** 方法。它返回一个未初始化(任意)数据的数组,其形状和类型与原型相同。这里第一个参数是原型(类数组)的形状和数据类型,它们定义了返回数组的这些相同属性。我们使用“**order**”参数设置了顺序。
order 参数会覆盖结果的内存布局。“C”表示 C 顺序,“F”表示 F 顺序,“A”表示如果原型是 Fortran 连续的则为“F”,否则为“C”。“K”表示尽可能匹配原型的布局。shape 参数会覆盖结果的形状。如果 order='K' 并且维度数量不变,则会尝试保持顺序,否则,order='C' 为隐含的。overrides 参数会覆盖结果的数据类型。
如果 subok 参数为 True,则新创建的数组将使用原型的子类类型,否则它将是基类数组。默认为 True。
步骤
首先,导入所需的库:
import numpy as np
使用 array() 方法创建一个 NumPy 三维数组。我们添加了 int 类型的元素:
arr = np.array([[[5,10],[15,20]],[[25,30],[35,40]],[[50,60],[70,80]]])
显示数组:
print("Array...
",arr)获取数组的类型:
print("
Array type...
", arr.dtype)
获取数组的维度:
print("
Array Dimensions...
", arr.ndim)要返回一个与给定数组具有相同形状和类型的新数组,请在 Python NumPy 中使用 numpy.empty_like() 方法。我们使用“order”参数设置了顺序:
newArr = np.empty_like(arr, order = 'C')
print("
New Array..
", newArr)获取新数组的类型:
print("
New Array type...
", newArr.dtype)
获取新数组的维度:
print("
New Array Dimensions...
", newArr.ndim)示例
import numpy as np
# Creating a numpy Three-Dimensional array using the array() method
# We have added elements of int type
arr = np.array([ [[5,10],[15,20]], [[25,30],[35,40]], [[50,60],[70,80]] ])
# 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 a new array with the same shape and type as a given array, use the numpy.empty_like() method in Python Numpy
# It returns the array of uninitialized (arbitrary) data with the same shape and type as prototype.
# The 1st parameter here is the shape and data-type of prototype(array-like) that define these same attributes of the returned array.
# We have set the order using the "order" parameter
newArr = np.empty_like(arr, order = 'C')
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... [[[ 5 10] [15 20]] [[25 30] [35 40]] [[50 60] [70 80]]] Array type... int64 Array Dimensions... 3 New Array.. [[[ 0 0] [ 0 0]] [[140556668570992 140556671038576] [140556668571056 140556668441520]] [[140556668441712 140556668441776] [140556668441840 140556668442416]]] New Array type... int64 New Array Dimensions... 3
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP