有一个Python函数可以将数组中的每一行都除以该行的第一个值吗?

huangapple go评论72阅读模式
英文:

Is there a python function that will divide each row in an array by that rows first value?

问题

我需要将一个50x50的数组中的每一行都除以该行的第一个值,以便通过每行的第一个值来归一化数组的行。例如,如果我有一个数组:

[A1,A2,A3];
[B1,B2,B3];
[C1,C2,C3]

我需要将A行中的所有值除以A1,将B行中的所有值除以B1,将C行中的所有值除以C1。

英文:

I need to divide each row in a 50x50 array by the first value in each row in order to normalize the rows of my array by the first value of each row. So for instance if I have an array of:

[A1,A2,A3];
[B1,B2,B3];
[C1,C2,C3]

I would need to divide all values in the A-Row by A1, all values in B-Row by B1, and all values in C-Row by C1.

答案1

得分: 0

基本的Python不具备数组,而是使用列表的列表。请使用NumPy数组。

import numpy as np

my_np_array = np.array([[2, 4, 10, 16], [4, 12, 16, 8], [3, 9, 21, 3]])

result = (my_np_array.T / my_np_array[:, 0]).T

print(my_np_array)
print(result)

结果为:

[[ 2  4 10 16]
 [ 4 12 16  8]
 [ 3  9 21  3]]
[[1. 2. 5. 8.]
 [1. 3. 4. 2.]
 [1. 3. 7. 1.]]
英文:

Basic python does not have arrays - it has Lists of Lists. Use a numpy array.

import numpy as np

my_np_array = np.array([[2,4,10,16],[4,12,16,8], [3,9,21,3]])

result = (my_np_array.T/my_np_array[:,0]).T

print(my_np_array)
print(result)

gives

[[ 2  4 10 16]
 [ 4 12 16  8]
 [ 3  9 21  3]]
[[1. 2. 5. 8.]
 [1. 3. 4. 2.]
 [1. 3. 7. 1.]]

huangapple
  • 本文由 发表于 2023年6月6日 00:26:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76408342.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定