使用 `np.diff` 但假设输入以额外的零开头 [英] Use `np.diff` but assume the input starts with an extra zero
问题描述
给定一系列事件时间 v
,我可以使用 np.diff(v)
创建它们的间隔持续时间.有没有办法让 np.diff
假设系列以隐式 0.
开头,以便它生成一个与 v<具有相同长度的数组/代码>?
手动解决方法是:
def diff_from_zero(v):返回 np.diff(np.hstack(([0.], v)))
有没有办法使用 diff
或其他函数来获得相同的结果?
举个例子:
t = np.array([1.1, 2.0, 4.5, 4.9, 5.2])
我们要计算 t
中的连续差异,包括从 0.
到 t
中第一个元素的差异.
问题给出了实现此目的的方式:
<预><代码>>>>np.diff(np.hstack((0, t)))也可能是这样:
<预><代码>>>>np.hstack((t[0], np.diff(t)))但是名字模糊的函数ediff1d
可以在一个函数调用中完成:
将 t[0]
添加到结果中与计算 t[0] - 0 的差值相同.
,当然.(假设 t
为非空).
时间(不是问题的动机,但我很好奇)
将 numpy 导入为 npt = np.random.randn(10000)%timeit np.diff(np.concatenate(([0], t)))10000 个循环,最好的 3 个:每个循环 23.1 µs%timeit np.diff(np.hstack((0, t)))10000 个循环,最好的 3 个:每个循环 31.2 µs%timeit np.ediff1d(t, to_begin=t[0])10000 个循环,最好的 3 个:每个循环 92 µs
Given a series of event times v
, I can create their interval durations using np.diff(v)
. Is there a way to have np.diff
assume the series starts with an implicit 0.
, so that it produces an array that has the same length as v
?
A manual workaround is:
def diff_from_zero(v):
return np.diff(np.hstack(([0.], v)))
Is there a way to use diff
or another function to have the same result?
Given for example:
t = np.array([1.1, 2.0, 4.5, 4.9, 5.2])
We want to compute the consecutive differences in t
, including the diff from 0.
to the first element in t
.
The question gave this way of accomplishing this:
>>> np.diff(np.hstack((0, t)))
And it could be this too:
>>> np.hstack((t[0], np.diff(t)))
But the obscurely-named function ediff1d
can do it in one function call:
>>> np.ediff1d(t, to_begin=t[0])
array([ 1.1, 0.9, 2.5, 0.4, 0.3])
Prepending t[0]
to the result is the same as computing the difference t[0] - 0.
, of course. (Assuming t
is nonempty).
Timings (not the motivation of the question, but I was curious)
import numpy as np
t = np.random.randn(10000)
%timeit np.diff(np.concatenate(([0], t)))
10000 loops, best of 3: 23.1 µs per loop
%timeit np.diff(np.hstack((0, t)))
10000 loops, best of 3: 31.2 µs per loop
%timeit np.ediff1d(t, to_begin=t[0])
10000 loops, best of 3: 92 µs per loop
这篇关于使用 `np.diff` 但假设输入以额外的零开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!