简体   繁体   English

减去二维数组中每一行的第一个元素

[英]Subtracting first element of each row in a 2D array

I'm using Python.我正在使用 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.例如,第 1 行:20.28466797 - 20.28466797、19.24307251- 20.28466797、20.87997437 - 20.28466797 等第 2 行:4.4154,3544.3544.3544.3544.3544.34544

您可以使用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]]

暂无
暂无

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

相关问题 从字典中2d数组中的每个元素中减去一个值 - Subtracting a value from each element in a 2d array within a dictionary 如何从二维数组中返回每个元素的行索引? - How to return the row index of each element from a 2D array? 如何使用二维数组每一行的元素压缩一维数组中的每个元素? - How to zip each element from a 1D array with the elements from each row of a 2D array? Pytorch:如何在二维张量的每一行中找到第一个非零元素的索引? - Pytorch: How can I find indices of first nonzero element in each row of a 2D tensor? Numpy 按降序对二维数组进行排序并从每行中取前 N - Numpy sorting 2d array by descending and take first N from each row Numpy索引:第一个(变化的)2d数组中每行的元素数 - Numpy indexing: first (varying) number of elements from each row in 2d array 仅当满足每行元素上的条件时,才计算2D数组特定列的均值和方差 - Compute mean and variance on specific columns of 2D array only if a condition on element on each row is satisfied Numpy 检查二维 numpy 数组每一行的所有元素是否相同 - Numpy check that all the element of each row of a 2D numpy array is the same 将2D numpy数组的每一行导出为csv列中的单个元素 - Exporting each row of a 2D numpy array as a single element in csv column 如何从二维numpy数组的每一行中获取元素的首次出现? - how to get the first occurring of an element from every row in a 2D numpy array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM