kanayamalakar
kanayamalakar

Reputation: 574

Shifted array subtraction in numpy

I have two arrays

A = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
B = np.array([6, 7, 8, 9, 1, 2, 3, 4, 5])

I need to subtract A from B but not in the normal way. I need to subtract 0th element of A from 4th element of B, 1st element of A from 5th element of B i.e. B[4] - A[0] , B[5] - A[1] , ... , B[n] - A[n-4] and so on. In short I need to shift elements of A by 4 indices and subtract from B and wrap the difference around. Is there a easy way to do this in python?

Upvotes: 1

Views: 3603

Answers (2)

Francisco
Francisco

Reputation: 11486

You can use numpy.roll:

numpy.roll(B, -4) - A

If you don't need to wrap around, you can use something like:

>>> B[4:] - A[:-4]
array([0, 0, 0, 0, 0])

Upvotes: 3

lorenzori
lorenzori

Reputation: 747

if you convert the array into a pandas Series you can use the shift() method.

Upvotes: 0

Related Questions