在NumPy中返回一個具有給定形狀,並填充為1的新陣列


要在Python NumPy中返回一個具有給定形狀和型別的、填充為1的新陣列,可以使用**numpy.ones()**方法。第一個引數設定新陣列的形狀。

該函式返回一個具有給定形狀、dtype和order的、填充為1的陣列。dtype引數是陣列所需的數 據型別,例如numpy.int8。預設為numpy.float64。order引數指定是否以行優先(C風格)或列優先(Fortran風格)的順序在記憶體中儲存多維資料。

NumPy 提供了全面的數學函式、隨機數生成器、線性代數例程、傅立葉變換等等。它支援各種硬體和計算平臺,並且可以很好地與分散式、GPU和稀疏陣列庫配合使用。

步驟

首先,匯入所需的庫:

import numpy as np

要在Python NumPy中返回一個具有給定形狀和型別的、填充為1的新陣列,可以使用numpy.ones()方法。第一個引數設定新陣列的形狀:

arr = np.ones((4))

顯示我們的陣列:

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
import numpy.ma as ma

# 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 shape of the new array
arr = np.ones((4))

# 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.]

Array datatype...
float64

Array Dimensions...
1

Our Array Shape...
(4,)

Elements in the Array...
4

更新於:2022年2月10日

120 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.