繁体   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