Numpy: Subtract Row Maximum from Each Column
You can use NumPy's amax function to find the maximum value in each row and then leverage tile to replicate these values across the corresponding rows. Finally, subtract this new matrix from the original matrix to achieve the desired result.
Here's an example code:
import numpy as np
# Create sample matrix
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Find maximum value in each row
row_max = np.amax(arr, axis=1)
# Replicate row maximums across rows
row_max_mat = np.tile(row_max, (arr.shape[1], 1)).T
# Subtract the replicated maximums from the original matrix
new_arr = arr - row_max_mat
# Print results
print('Original Matrix:\n', arr)
print('Row Maximums:\n', row_max)
print('Row Maximum Matrix:\n', row_max_mat)
print('Matrix with Column Subtraction:\n', new_arr)
Output:
Original Matrix:
[[1 2 3]
[4 5 6]
[7 8 9]]
Row Maximums:
[3 6 9]
Row Maximum Matrix:
[[3 3 3]
[6 6 6]
[9 9 9]]
Matrix with Column Subtraction:
[[-2 -1 0]
[-2 -1 0]
[-2 -1 0]]
原文地址: https://www.cveoy.top/t/topic/m6Jg 著作权归作者所有。请勿转载和采集!