在NumPy中返回指定區間內的等間距數字


要在指定區間內返回等間距的數字,請使用Python NumPy中的**numpy.linspace()**方法。第一個引數是“**start**”,即序列的起始值;第二個引數是“**end**”,即序列的結束值;第三個引數是**num**,即要生成的樣本數量。

除非將endpoint設定為False,否則stop是序列的結束值。在這種情況下,序列包含除最後一個num + 1個等間距樣本之外的所有樣本,因此stop被排除在外。請注意,當endpoint為False時,步長會發生變化。

dtype是輸出陣列的型別。如果未給出dtype,則資料型別將從start和stop推斷。推斷出的dtype永遠不會是整數;即使引數會生成整數陣列,也會選擇浮點數。結果中儲存樣本的軸。僅當start或stop為陣列狀時才相關。預設情況下(0),樣本將沿著插入到開頭的新的軸。使用-1在末尾獲取軸。

步驟

首先,匯入所需的庫:

import numpy as np

要在指定區間內返回等間距的數字,請使用Python NumPy中的numpy.linspace()方法:

arr = np.linspace(10, 20)
print("Array...
", arr)

獲取型別:

print("
Type...
", arr.dtype)

獲取維度:

print("
Dimensions...
",arr.ndim)

獲取形狀:

print("
Shape...
",arr.shape)

獲取元素數量:

print("
Number of elements...
",arr.size)

示例

import numpy as np

# To return evenly spaced numbers over a specified interval, use the numpy.linspace() method in Python Numpy
# The 1st parameter is the "start" i.e. the start of the sequence
# The 2nd parameter is the "end" i.e. the end of the sequence
# The 3rd parameter is the num i.s the number of samples to generate. Default is 50.
arr = np.linspace(10, 20)
print("Array...
", arr) # Get the type print("
Type...
", arr.dtype) # Get the dimensions print("
Dimensions...
",arr.ndim) # Get the shape print("
Shape...
",arr.shape) # Get the number of elements print("
Number of elements...
",arr.size)

輸出

Array...
[10.        10.20408163 10.40816327 10.6122449  10.81632653 11.02040816
11.2244898  11.42857143 11.63265306 11.83673469 12.04081633 12.24489796
12.44897959 12.65306122 12.85714286 13.06122449 13.26530612 13.46938776
13.67346939 13.87755102 14.08163265 14.28571429 14.48979592 14.69387755
14.89795918 15.10204082 15.30612245 15.51020408 15.71428571 15.91836735
16.12244898 16.32653061 16.53061224 16.73469388 16.93877551 17.14285714
17.34693878 17.55102041 17.75510204 17.95918367 18.16326531 18.36734694
18.57142857 18.7755102  18.97959184 19.18367347 19.3877551  19.59183673
19.79591837 20. ]

Type...
float64

Dimensions...
1

Shape...
(50,)

Number of elements...
50

更新於:2022年2月8日

236 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始學習
廣告