在 Numpy 中返回一個具有給定形狀、填充值和不同輸出型別的新陣列
要返回一個具有給定形狀和型別的新陣列,並用填充值填充,請在 Python Numpy 中使用 **numpy.full()** 方法。第一個引數是新陣列的形狀。第二個引數設定填充值。第三個引數用於設定返回的輸出陣列的所需資料型別。
dtype 是陣列所需的型別。order 表示是否以 C 或 Fortran 連續(行或列方式)順序在記憶體中儲存多維資料。
NumPy 提供了全面的數學函式、隨機數生成器、線性代數例程、傅立葉變換等。它支援各種硬體和計算平臺,並且可以很好地與分散式、GPU 和稀疏陣列庫配合使用。
步驟
首先,匯入所需的庫:
import numpy as np
要返回一個具有給定形狀和型別的新陣列,並用填充值填充,請使用 numpy.full() 方法。第三個引數用於設定返回的輸出陣列的所需資料型別:
arr = np.full((4,5), fill_value = 999, dtype = float)
顯示我們的陣列:
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)
示例
import numpy as np # To return a new array of given shape and type, filled with a fill value, use the numpy.full() method in Python Numpy # The 1st parameter is the shape of the new array # The 2nd parameter sets the fill value # The 3rd parameter is used to set the desired data-type of the returned output array arr = np.full((4,5), fill_value = 999, dtype = float) # 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)
輸出
Array... [[999. 999. 999. 999. 999.] [999. 999. 999. 999. 999.] [999. 999. 999. 999. 999.] [999. 999. 999. 999. 999.]] Array datatype... float64 Array Dimensions... 2 Our Array Shape... (4, 5) Elements in the Array... 20
廣告