Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

python - 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

question from:https://stackoverflow.com/questions/18594469/normalizing-a-pandas-dataframe-by-row

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

See pandas User Guide: Matching / broadcasting behavior


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...