简体   繁体   中英

Subtracting first element of each row in a 2D array

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.

您可以使用numpy.tile重复每行的第一个元素以创建矩阵并将其从原始矩阵中减去。

your_matrix - np.tile(your_matrix[:,:1], your_matrix.shape[0])

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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