在 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]]

更新於:2022年2月17日

915 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告