在 NumPy 中返回与给定数组具有相同形状和类型的完整数组


要返回与给定数组具有相同形状和类型的完整数组,请在 Python NumPy 中使用 **numpy.full_like()** 方法。第一个参数是形状和数据类型,定义返回数组的相同属性。第二个参数是填充值。

order 参数会覆盖结果的内存布局。“C”表示 C 顺序,“F”表示 F 顺序,“A”表示如果 a 是 Fortran 连续的则为“F”,否则为“C”。“K”表示尽可能接近地匹配 a 的布局。

subok 参数如果为 True,则新创建的数组将使用 a 的子类类型,否则它将是基类数组。默认为 True。shape 参数会覆盖结果的形状。如果 order='K' 且维度数量不变,则会尝试保持顺序,否则,将隐含 order='C'。

步骤

首先,导入所需的库 -

import numpy as np

使用 Python NumPy 中的 numpy.array() 方法创建一个新数组 -

arr = np.array([[91, 34, 89], [29, 87, 55]])

显示数组 -

print("Array...
",arr)

获取数组的类型 -

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

获取数组的维度 -

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

要返回与给定数组具有相同形状和类型的完整数组,请在 Python NumPy 中使用 numpy.full_like() 方法 -

newArr = np.full_like(arr, 999)
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([[91, 34, 89], [29, 87, 55]])

# 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 full array with the same shape and type as a given array, use the numpy.full_like() method in Python Numpy # The 1st parameter here is the shape and data-type, define these same attributes of the returned array. # The 2nd parameter is the fill value newArr = np.full_like(arr, 999) 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...
[[91 34 89]
[29 87 55]]

Array type...
int64

Array Dimensions...
2

New Array..
[[999 999 999]
[999 999 999]]

New Array type...
int64

New Array Dimensions...
2

更新于: 2022年2月10日

196 次查看

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.