在NumPy中返回一個具有給定形狀、填充1且資料型別不同的新陣列
要返回一個具有給定形狀和型別、填充1的新陣列,請在Python NumPy中使用**numpy.ones()**方法。第一個引數設定行數,第二個引數設定列數。這兩個引數共同構成陣列的形狀。“**dtype**”引數用於設定陣列所需的資料型別。
該函式返回一個具有給定形狀、dtype和順序的填充1的陣列。順序表示是否以行主序(C風格)或列主序(Fortran風格)在記憶體中儲存多維資料。
NumPy提供全面的數學函式、隨機數生成器、線性代數例程、傅立葉變換等等。它支援各種硬體和計算平臺,並且與分散式、GPU和稀疏陣列庫相容良好。
步驟
首先,匯入所需的庫:
import numpy as np
要返回一個具有給定形狀和型別、填充1的新陣列,請在Python NumPy中使用numpy.ones()方法。“dtype”引數用於設定陣列所需的資料型別:
arr = np.ones((4,5), dtype = int)
顯示陣列:
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 ones, use the numpy.ones() method in Python Numpy # The 1st parameter sets the number of rows # The 2nd parameter sets the number of columns # Both 1st and 2nd parameters forms the shape of the array # The "dtype" parameter is used to set the desired data-type for the array arr = np.ones((4,5), dtype = int) # 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... [[1 1 1 1 1] [1 1 1 1 1] [1 1 1 1 1] [1 1 1 1 1]] Array datatype... int64 Array Dimensions... 2 Our Array Shape... (4, 5) Elements in the Array... 20
廣告