Subtracting first element of each row in a 2D array

NeuroKween :

I'm using Python. I have an array (below)

array([[20.28466797, 19.24307251, 20.87997437, ..., 20.38343811,
    19.70025635, 20.22036743],
   [ 4.21954346, 17.05456543, 10.09838867, ..., 19.50102234,
    19.62188721, 18.30804443],
   [14.44546509, 19.43798828, 19.45491028, ..., 22.08952332,
    17.83691406, 17.86752319])

I'm looking to write a code that will take the first element of each row, and subtract each value in the row from it.

Eg, row 1: 20.28466797 - 20.28466797, 19.24307251- 20.28466797, 20.87997437 - 20.28466797, etc. row 2: 4.21954346 -4.21954346, 17.05456543 - 4.21954346, etc.

ABarrier :

The following will do the job for you:

import numpy as np

def array_fun(arr):
    # compute the length of the given array
    n = len(arr)
    m = len(arr[0])

    # create an empty list
    aList = []

    # append by substracting the first element
    [aList.append(arr[i][j]-arr[i][0]) for i in range(n) for j in range(m)]

    # return modified array
    return np.array(aList).reshape(n,m)

if __name__ == "__main__":
    # define your array
    arr = [[1, 3, 7], [1, 1, 2], [5, 2, 2]]

    # print initial array
    print(np.array(arr))

    # print modified array
    print(np.array(array_fun(arr)))

Initial array:

[[1 3 7]
 [1 1 2]
 [5 2 2]]

Final array:

[[ 0  2  6]
 [ 0  0  1]
 [ 0 -3 -3]]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=4027&siteId=1