2

This is gonna be a fairly simple question to which I wonder if there is a quick and clean workaround in Python.

Let say I have a nd-array defined as such:

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]]])

Then I calculate the difference between a value and the previous value in the array for the 3rd dimension as follow:

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]]])

Is it possible to come back to the original values using a similar technique or do I have to use a for loop and temporary variables?

For example, this doesn't do the trick:

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]]])

1 Answer 1

6

First, to compute the difference, instead of

C[:, :, 1:] - C[:, :, 0:C.shape[2]-1]

you could use 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

Next, if you know you want to retrieve the original C, perhaps it is better not to overwrite the values in the first place. Just save the differences in a separate array:

E = np.diff(C, axis = -1)

After all, there is no quicker way to perform a calculation than to not compute at all :).

But if you really do want to overwrite the values, then, to retrieve the original values, use 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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.