Search code examples
pythonmultidimensional-arraymatrix-multiplication

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


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.


Solution

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