ChrisB ChrisB - 2 years ago 567
Python Question

Normalizing a pandas DataFrame by row

What is the most idiomatic way to normalize each row of a pandas DataFrame? Normalizing the columns is easy, so one (very ugly!) option is

(df.T / df.T.sum()).T

Pandas broadcasting rules prevent
df / df.sum(axis=1)
from doing this

Answer Source

To overcome the broadcasting issue, you can use the div method:

df.div(df.sum(axis=1), axis=0)


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download