这将是一个相当简单的问题,我想知道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]]])
答案 0 :(得分:6)
首先,计算差异,而不是
C[:, :, 1:] - C[:, :, 0:C.shape[2]-1]
您可以使用numpy.diff:
np.diff(C, axis = -1)
In [27]: C = np.random.rand(2,3,3)
In [28]: D = C[:, :, 1:] - C[:, :, 0:C.shape[2]-1]
In [29]: E = np.diff(C, axis = -1)
In [30]: np.allclose(D, E)
Out[30]: True
接下来,如果您知道要检索原始C
,最好不要首先覆盖这些值。只需将差异保存在单独的数组中:
E = np.diff(C, axis = -1)
毕竟,没有更快的方法来执行计算而不是根本不计算:)。
但如果您确实想覆盖这些值,那么要检索原始值,请使用np.cumsum:
In [20]: C = np.random.rand(2,3,3)
In [21]: D = C.copy()
In [22]: C[:, :, 1:] = np.diff(C, axis = -1)
In [23]: C = np.cumsum(C, axis = -1)
In [24]: np.allclose(C,D)
Out[24]: True