在 NumPy 中复制数组的值
要在 Python NumPy 中复制一个数组的值到另一个数组,根据需要进行广播,可以使用 numpy.copyto() 方法。
- 第一个参数是源数组。
- 第二个参数是目标数组。
casting 参数控制复制时允许进行哪种数据类型转换。
- ‘no’ 表示数据类型不允许转换。
- ‘equiv’ 表示只允许字节序更改。
- ‘safe’ 表示只允许能够保留值的转换。
- ‘same_kind’ 表示只允许安全的转换或同类型内的转换,例如 float64 到 float32。
- ‘unsafe’ 表示允许进行任何数据转换。
步骤
首先,导入所需的库。
import numpy as np
创建一个二维数组。
arr = np.array([[28, 49, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69 ], [69, 80, 80, 99]])
显示我们的数组。
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)目标数组。
arrRes = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
要复制一个数组的值到另一个数组,根据需要进行广播,可以使用 numpy.copyto() 方法。
res = np.copyto(arr, arrRes)
print("
Result...
",arrRes)示例
import numpy as np
# Create a 2d array
arr = np.array([[28, 49, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69], [69, 80, 80, 99]])
# 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)
# The destination
arrRes = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15,16]]
# To copy values from one array to another, broadcasting as necessary, use the numpy.copyto() method in Python Numpy
# The 1st parameter is the source array
# The 2nd parameter is the destination array
res = np.copyto(arr, arrRes)
print("
Result...
",arrRes)输出
Array... [[28 49 78 88] [92 81 98 45] [22 67 54 69] [69 80 80 99]] Array datatype... int64 Array Dimensions... 2 Our Array Shape... (4, 4) Elements in the Array... 16 Result... [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP