python - 我怎样才能在numpy中找到减法和

标签 python numpy time-series

我想在每日报告中使用 numpy 函数,因为我的数据非常大。

假设我有一个 numpy 二维数组

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

我想做这样的事情

abs(array([0, 1, 2]) - array([[3, 4, 5], [4, 5, 6], ..., [7, 8, 9]])).sum()
abs(array([1, 2, 3]) - array([[4, 5, 6], [5, 6, 7], ..., [7, 8, 9]])).sum()
...
abs(array([3, 4, 5]) - array([[0, 1, 2], [6, 7, 8], [7, 8, 9]])).sum()
abs(array([4, 5, 6]) - array([[0, 1, 2], [1, 2, 3], [7, 8, 9]])).sum()
...
abs(array([7, 8, 9]) - array([[0, 1, 2], [1, 2, 3], ..., [4, 5, 6]])).sum()

我试过了,但不能跳过左侧数组中任何元素位于右侧数组中的数组。

for i in range(len(A)):
    temp = np.roll(A, -i, axis=0)
    print(abs(temp[0] - temp[3:]).sum())

这是预期的结果

results = [75, 54, ..., 30, 30, ...75]

对不起,我的英文解释很差,谢谢。

最佳答案

如果您希望拥有一个仅涉及 NumPy 功能的简单单行解决方案,我建议您这样做:

import numpy as np

results = np.apply_along_axis(arr=A, 
                              axis=1, 
                              func1d=lambda x: 
                               np.abs(x - A[~np.isin(A, x).any(axis=1),:]).sum()
                              )

结果符合预期:

array([75, 54, 36, 30, 30, 36, 54, 75])

关于python - 我怎样才能在numpy中找到减法和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56610419/

相关文章:

python - “元组”对象没有属性 'layer'

python - 如何在 Python 中从 mp4 视频中获取一随机帧?

numpy.genfromtxt 无法正确读取 bool 数据

python - 如何广播或矢量化使用 scipy.ndimage map_coordinates 的 2D 数组的线性插值?

python - 使用 'fixed points' 在 Python 中插入数据

scala - 如何进行时间序列简单预测?

python - 单独替换pandas.dataframe中的NaN

python - cx_卡住。安装后如何安装服务和执行脚本

python - 使用随机整数创建 numpy 数组,每行具有另一个范围

r - 在 R 中合并两个不同的数据帧