Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

I checked a while back for questions relevant to my own about normalizing numpy arrays but couldn't find any. So I'll pose my question following this line of code:

for i in range(arraytransition.shape[0]):
    total = 0.0
    for i in range(arraytransition.shape[1]):
        total += arraytransition[i, j]
    for i in range(arraytransition.shape[1]):
        arraytransition[i, j] /= total

'arraytransition' is the array in question. I understand that the code lacks efficiency, but I'm not fluent enough with numpy at the moment to use a more efficient code (I tried but failed). The current problem with this code is that it reproduces each row as totally identical.

What are the potential fixes to this block of code? I would also be happy to know a more efficient way of doing things.

Thanks! This is my first post here and I hope I am

  1. posting original material
  2. following all of the appropriate guidelines

If not, please indicate to me what I am doing wrong and I would be happy to correct myself.

share|improve this question
    
If you want answers maybe programmers.stackexchange.com/help/no-one-answers could help. –  BFaceCoder Jul 3 at 6:34

1 Answer 1

You would probably be well-served looking through the numpy documentation, the library has a lot of optimised ways of doing simple and complex operations on ndarrays that avoid using multiple for-loops.

You could just do this to achieve the same thing:

import numpy as np

total = np.sum(arraytransition)
arraytransition_normalised = arraytransition / total

This will calculate the sum of the ndarray and then divide each element of the array element-wise by the sum of the elements of that matrix.

There is also the linalg.norm function, however I think you are using a different definition of normalisation.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.