是否有一个 numpy 函数可以让您指定开始、步骤和编号? [英] Is there a numpy function that allows you to specify start, step, and number?

查看:26
本文介绍了是否有一个 numpy 函数可以让您指定开始、步骤和编号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都熟悉 np.linspace,它创建一个给定 startstopnum<的数组/code> 元素:

We're all familiar with np.linspace, which creates an array given a start, stop, and num of elements:

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<的数组/代码>:

Likewise, who could ever forget np.arange, which creates an array given a start, stop, and step:

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 个元素,同时省略 停止?应该有.

But is there a function that allows you to specify a start, step, and num of elements, while omitting the stop? There should be.

推荐答案

一个被删除的回答指出 linspace 需要一个 endpoint 参数.

A deleted answer pointed out that linspace takes an endpoint parameter.

有了这个,其他答案中给出的两个例子可以写成:

With that, 2 examples given in other answers can be written as:

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 中定义的函数,了解有关如何生成范围和/或网格的其他想法.例如,np.ogrid[0:10:9j] 的行为类似于 linspace.

Look at the functions defined in numpy.lib.index_tricks for other ideas on how to generate ranges and/or grids. For example, np.ogrid[0:10:9j] behaves like linspace.

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

这篇关于是否有一个 numpy 函数可以让您指定开始、步骤和编号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆