簡體   English   中英

是否有一個 numpy 函數可以讓您指定開始、步驟和編號?

[英]Is there a numpy function that allows you to specify start, step, and number?

我們都熟悉np.linspace ,它創建一個給定startstopnum元素的數組:

In [1]: import numpy as np

In [2]: np.linspace(0, 10, 9)
Out[2]: array([  0.  ,   1.25,   2.5 ,   3.75,   5.  ,   6.25,   7.5 ,   8.75,  10.  ])

同樣,誰能忘記np.arange ,它會創建一個給定startstopstep的數組:

In [4]: np.arange(0, 10, 1.25)
Out[4]: array([ 0.  ,  1.25,  2.5 ,  3.75,  5.  ,  6.25,  7.5 ,  8.75])

但是是否有一個函數允許您指定元素的startstepnum ,同時省略stop 應該有。

謝謝你的問題。 我遇到過同樣的問題。 (從我的角度來看)最短和最優雅的方式是:

import numpy as np
start=0
step=1.25
num=9

result=np.arange(0,num)*step+start

print(result)

返回

[  0.     1.25   2.5    3.75   5.     6.25   7.5    8.75  10.  ]

一個刪除的答案指出linspace需要一個endpoint參數。

有了這個,其他答案中給出的 2 個例子可以寫成:

In [955]: np.linspace(0, 0+(0.1*3),3,endpoint=False)
Out[955]: array([ 0. ,  0.1,  0.2])

In [956]: np.linspace(0, 0+(5*3),3,endpoint=False)
Out[956]: array([  0.,   5.,  10.])

In [957]: np.linspace(0, 0+(1.25*9),9,endpoint=False)
Out[957]: array([  0.  ,   1.25,   2.5 ,   3.75,   5.  ,   6.25,   7.5 ,   8.75,  10.  ])

查看numpy.lib.index_tricks定義的函數, numpy.lib.index_tricks有關如何生成范圍和/或網格的其他想法。 例如, np.ogrid[0:10:9j]行為類似於linspace

def altspace(start, step, count, endpoint=False, **kwargs):
   stop = start+(step*count)
   return np.linspace(start, stop, count, endpoint=endpoint, **kwargs)
def by_num_ele(start,step,n_elements):
    return numpy.arange(start,start+step*n_elements,step)

也許?

這是一個應該始終與浮動一起使用的方法。

>>> import numpy as np
>>> import itertools
>>> def my_range(start, step, num):
...     return np.fromiter(itertools.count(start, step), np.float, num)
... 
>>> my_range(0, 0.1, 3)
array([ 0. ,  0.1,  0.2])

如果你想將它與浮點數以外的其他東西一起使用,你可以將np.float arg(或 kwarg):

>>> import numpy as np
>>> import itertools
>>> def my_range(start, step, num, dtype=np.float):
...     return np.fromiter(itertools.count(start, step), dtype, num)
... 
>>> my_range(0, 5, 3)
array([  0.,   5.,  10.])
>>> my_range(0, 5, 3, dtype=np.int)
array([ 0,  5, 10])

其他一些解決方案對我不起作用,因此由於我已經習慣使用np.linspace我決定將一個函數放在一起,用step參數替換linspacenum

def linspace(start, stop, step=1.):
  """
    Like np.linspace but uses step instead of num
    This is inclusive to stop, so if start=1, stop=3, step=0.5
    Output is: array([1., 1.5, 2., 2.5, 3.])
  """
  return np.linspace(start, stop, int((stop - start) / step + 1))

示例輸出:

linspace(9.5, 11.5, step=.5)
array([ 9.5, 10. , 10.5, 11. , 11.5])

編輯:我誤讀了這個問題,最初的問題想要一個省略stop參數的函數。 我仍然會把這個留在這里,因為我認為它可能對一些偶然發現這個問題的人有用,因為它是我發現的唯一一個類似於我最初的問題,即尋找具有startstopstep的函數,而不是比num

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM