英文:
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.]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论