这将是一个相当简单的问题,我想知道 Python 中是否有一个快速而干净的解决方法。
假设我有一个这样定义的nd-array:
In [10]: C = np.random.rand(2,3,3)
In [11]: C
Out[11]:
array([[[ 0.43588471, 0.06600133, 0.81145749],
[ 0.20270693, 0.85879686, 0.75778422],
[ 0.68253449, 0.98287412, 0.63804605]],
[[ 0.61591433, 0.36453861, 0.23798795],
[ 0.26761896, 0.00657165, 0.04083067],
[ 0.11177481, 0.55245769, 0.97274592]]])
然后我计算第三维数组中一个值与前一个值之间的差异,如下所示:
In [12]: C[:, :, 1:] = C[:, :, 1:] - C[:, :, 0:C.shape[2]-1]
In [13]: C
Out[13]:
array([[[ 0.43588471, -0.36988337, 0.74545616],
[ 0.20270693, 0.65608994, -0.10101264],
[ 0.68253449, 0.30033963, -0.34482807]],
[[ 0.61591433, -0.25137572, -0.12655065],
[ 0.26761896, -0.26104731, 0.03425902],
[ 0.11177481, 0.44068288, 0.42028823]]])
是否可以使用类似的技术恢复原始值,还是必须使用 for 循环和临时变量?
例如,这不能解决问题:
In [15]: C[:, :, 1:] = C[:, :, 0:C.shape[2]-1] + C[:, :, 1:]
In [16]: C
Out[16]:
array([[[ 0.43588471, 0.06600133, 0.37557278],
[ 0.20270693, 0.85879686, 0.5550773 ],
[ 0.68253449, 0.98287412, -0.04448843]],
[[ 0.61591433, 0.36453861, -0.37792638],
[ 0.26761896, 0.00657165, -0.22678829],
[ 0.11177481, 0.55245769, 0.86097111]]])