Numpy 的 diff(~)
方法计算输入数组中每个值与其相邻值之间的差异。
参数
1. a
| array-like
输入数组。
2. n
| int
| optional
您想要递归计算的差异数。默认情况下,n=1
。请查看下面的示例以进行说明。
3. axis
| int
| optional
计算差异的轴。对于二维数组,允许的值如下:
轴 |
意义 |
---|---|
0 |
将按列计算差异 |
1 |
差异将按行计算 |
默认情况下,该轴等于最后一个轴。这意味着,对于 2D 数组,axis=1
。
4. prepend
| array-like
| optional
您希望在计算差异之前添加到输入数组 a 之前的值。
返回值
一个 Numpy 数组,包含输入数组中每个值与其相邻值之间的差异。
例子
基本用法
a = np.array([1, 3, 8, 15, 30])
np.diff(a)
array([ 2, 5, 7, 15])
递归计算差异
假设我们要递归计算两次差异,即 n=2
。 diff(~)
首先计算 n=1
时的情况,然后对其输出执行另一个 diff(~)
。
n=1
时的情况:
a = np.array([1, 3, 8, 15, 30])
np.diff(a, n=1)
array([ 2, 5, 7, 15])
n=2
时的情况:
a = np.array([1, 3, 8, 15, 30])
np.diff(a, n=2)
array([3, 2, 8])
观察 n=2
只是在 n=1
的输出上应用 diff 方法。
计算二维数组的差异
考虑以下二维数组
a = np.array([[1, 3], [8, 15]])
a
array([[ 1, 3],
[ 8, 15]])
逐行
np.diff(a) # or axis=1
array([[2],
[7]])
按列
np.diff(a, axis=0)
array([[ 7, 12]])
在计算之前预置值
a = np.array([3, 8, 15, 30])
np.diff(a, prepend=1)
array([ 2, 5, 7, 15])
在这里,我们将值 1 添加到 a
前面,因此本质上我们正在计算 [1,3,8,15,30]
的差异。
相关用法
- Python difflib.unified_diff用法及代码示例
- Python difflib.get_close_matches用法及代码示例
- Python difflib.ndiff用法及代码示例
- Python difflib.SequenceMatcher.get_opcodes用法及代码示例
- Python difflib.context_diff用法及代码示例
- Python difflib.SequenceMatcher.find_longest_match用法及代码示例
- Python difflib.restore用法及代码示例
- Python difflib.SequenceMatcher.get_matching_blocks用法及代码示例
- Python distributed.protocol.serialize.register_generic用法及代码示例
- Python distributed.get_task_metadata用法及代码示例
- Python distributed.Client.gather用法及代码示例
- Python distributed.recreate_tasks.ReplayTaskClient.recreate_task_locally用法及代码示例
- Python distributed.diagnostics.plugin.SchedulerPlugin用法及代码示例
- Python distributed.Client.ncores用法及代码示例
- Python distributed.Client.retire_workers用法及代码示例
- Python distributed.Client.unregister_worker_plugin用法及代码示例
- Python distributed.fire_and_forget用法及代码示例
- Python dir用法及代码示例
- Python distributed.Client.set_metadata用法及代码示例
- Python dictionary cmp()用法及代码示例
- Python distributed.Client.scheduler_info用法及代码示例
- Python distributed.Client.submit用法及代码示例
- Python distributed.Client.compute用法及代码示例
- Python distributed.SpecCluster.scale用法及代码示例
- Python distributed.get_worker用法及代码示例
注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 NumPy | diff method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。