首页 > 解决方案 > Is there a way to subtract 'a - b' instead of 'b - a' as with np.diff?

问题描述

I am looking for an arithmetic function plus possibly the usage of absolute values to compute 'a - b'. I know 'np.diff' does 'b - a'. That is the second element minus the first element and so forth.

From the original array:

[79 54 74 62 85 55 88 85 51 85 54 84 78 47 83 52 62 84 52 79 51 47 78 69
 74 83 55 76 78 79 73 77 66 80 74 52 48 80 59 90 80 58 84 58 73 83 64 53
 82 59 75 90 54 80 54 83 71 64 77 81 59 84 48 82 60 92 78 78 65 73 82 56
 79 71 62 76 60 78 76 83 75 82 70 65 73 88 76 80 48 86 60 90 50 78 63 72
 84 75 51 82 62 88 49 83 81 47 84 52 86 81 75 59 89 79 59 81 50 85 59 87
 53 69 77 56 88 81 45 82 55 90 45 83 56 89 46 82 51 86 53 79 81 60 82 77
 76 59 80 49 96 53 77 77 65 81 71 70 81 93 53 89 45 86 58 78 66 76 63 88
 52 93 49 57 77 68 81 81 73 50 85 74 55 77 83 83 51 78 84 46 83 55 81 57
 76 84 77 81 87 77 51 78 60 82 91 53 78 46 77 84 49 83 71 80 49 75 64 76
 53 94 55 76 50 82 54 75 78 79 78 78 70 79 70 54 86 50 90 54 54 77 79 64
 75 47 86 63 85 82 57 82 67 74 54 83 73 73 88 80 71 83 56 79 78 84 58 83
 43 60 75 81 46 90 46 74]

This is what I get with np.diff :

array([-25,  20, -12,  23, -30,  33,  -3, -34,  34, -31,  30,  -6, -31,
        36, -31,  10,  22, -32,  27, -28,  -4,  31,  -9,   5,   9, -28,
        21,   2,   1,  -6,   4, -11,  14,  -6, -22,  -4,  32, -21,  31,
       -10, -22,  26, -26,  15,  10, -19, -11,  29, -23,  16,  15, -36,
        26, -26,  29, -12,  -7,  13,   4, -22,  25, -36,  34, -22,  32,
       -14,   0, -13,   8,   9, -26,  23,  -8,  -9,  14, -16,  18,  -2,
         7,  -8,   7, -12,  -5,   8,  15, -12,   4, -32,  38, -26,  30,
       -40,  28, -15,   9,  12,  -9, -24,  31, -20,  26, -39,  34,  -2,
       -34,  37, -32,  34,  -5,  -6, -16,  30, -10, -20,  22, -31,  35,
       -26,  28, -34,  16,   8, -21,  32,  -7, -36,  37, -27,  35, -45,
        38, -27,  33, -43,  36, -31,  35, -33,  26,   2, -21,  22,  -5,
        -1, -17,  21, -31,  47, -43,  24,   0, -12,  16, -10,  -1,  11,
        12, -40,  36, -44,  41, -28,  20, -12,  10, -13,  25, -36,  41,
       -44,   8,  20,  -9,  13,   0,  -8, -23,  35, -11, -19,  22,   6,
         0, -32,  27,   6, -38,  37, -28,  26, -24,  19,   8,  -7,   4,
         6, -10, -26,  27, -18,  22,   9, -38,  25, -32,  31,   7, -35,
        34, -12,   9, -31,  26, -11,  12, -23,  41, -39,  21, -26,  32,
       -28,  21,   3,   1,  -1,   0,  -8,   9,  -9, -16,  32, -36,  40,
       -36,   0,  23,   2, -15,  11, -28,  39, -23,  22,  -3, -25,  25,
       -15,   7, -20,  29, -10,   0,  15,  -8,  -9,  12, -27,  23,  -1,
         6, -26,  25, -40,  17,  15,   6, -35,  44, -44,  28])

Desired output: Basically 'a - b', which for example with the first value instead of a -25, should be a '25'

标签: pythonnumpy

解决方案


或者你可以把你得到的否定:-np.diff(x)


推荐阅读