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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。