简体   繁体   English

numpy中的移位数组减法

[英]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. 我需要从B中减去A,但不是正常方式。 I need to subtract 0th element of A from 4th element of B, 1st element of A from 5th element of B ie B[4] - A[0] , B[5] - A[1] , ... , B[n] - A[n-4] and so on. 我需要从B的第4个元素中减去A的第0个元素,从B的第5个元素中减去A的第一个元素,即B[4] - A[0] , B[5] - A[1] , ... , B[n] - A[n-4] ,依此类推。 In short I need to shift elements of A by 4 indices and subtract from B and wrap the difference around. 简而言之,我需要将A的元素移位4个索引,并从B中减去并环绕差。 Is there a easy way to do this in python? 有没有一种简单的方法可以在python中做到这一点?

You can use numpy.roll : 您可以使用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])

如果将数组转换为Pandas Series,则可以使用shift()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM