1

I have a np.array stored in a variable, x, which looks like below:

array([[ 956],
       [ 929],
       [1083],
       [1074],
       [ 922]]

I want to subtract every number from the previous number, and I want a new variable, y, to look like below:

array([[ -27],
       [ 154],
       [  -9],
       [-152]]
tobias_k
  • 81,265
  • 12
  • 120
  • 179
Ryo
  • 157
  • 2
  • 3
  • 15

1 Answers1

3
import numpy as np 

x = np.array([[ 956],
       [ 929],
       [1083],
       [1074],
       [ 922]] 

out = np.diff(out, axis=0)

Out: array([[ -27],
   [ 154],
   [  -9],
   [-152]]
Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
  • 1
    Or `np.diff(a, axis=0)` (in this case, you don't need `hstack` and `L`) – tobias_k Feb 10 '17 at 15:44
  • 1
    When you use the `axis` parameter, you don't need to do `hstack` and the `L = ...` comprehension. Just `np.diff(x, axis=0)` and nothing else. See [documentation](https://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html) – tobias_k Feb 10 '17 at 15:48
  • @tobias_k, fixed. for a glance I thought it was a list of lists.... Not healthy to do multiple things. – Tony Tannous Feb 10 '17 at 15:55
  • out = np.diff(_out_, axis=0) what is the second `out`? – 3kstc Feb 26 '18 at 22:04
  • @3kstc I simply overrode the out variable. `np.diff` took two parameters, and the return values I stored in `out`. – Tony Tannous Feb 26 '18 at 23:48
  • @TonyTannous Thanks, I'm [stuck](https://stackoverflow.com/questions/48998843/appending-to-a-new-column-the-differences-of-current-row-and-previous-row-for-m) with using the `diff`, any change you would you be able to help me out please? – 3kstc Feb 26 '18 at 23:52
  • @3kstc it is 02:20 am where I live and I need to wake up in 3 hours. I will take a look after I am back home (13~ hours from now). – Tony Tannous Feb 27 '18 at 00:21