Broadcasting in python

Example 1

Carolies from Carb, Proteins, Fats in 100g of different foods:

                  Apples    Beef      Eggs    Potatoes

where A is

> import numpy as np
> A=np.array([[56.0,0.0,4.4,68.0],
>           [1.2,104.0,52.0,8.0],
>           [1.8,135.0,99.0,0.9]])
> print(A)

Prints out

[[ 56.    0.    4.4  68. ]
 [  1.2 104.   52.    8. ]
 [  1.8 135.   99.    0.9]]

Calculate sum for each column

> cal=A.sum(axis=0) #axis=0 vertically
> print(cal)

Prints out

[ 59.  239.  155.4  76.9]

Then calculate percentages

> percentage=100*A/cal.reshape(1,4)
> print(percentage)

Prints out

[[94.91525424  0.          2.83140283 88.42652796]
 [ 2.03389831 43.51464435 33.46203346 10.40312094]
 [ 3.05084746 56.48535565 63.70656371  1.17035111]]

cal.reshape(1,4) is an example of python broadcasting, where where you take a matrix A. So this is a (3,4) matrix and you divide it by a (1,4) matrix. And technically, after this first line of codes cal, the variable cal, is already a (1,4) matrix. So technically you don’t need to call reshape here again

Example 2

Python will auto expand 100 to a (1,4) matrix of 100.

Example 3

                 Python will make

Example 4

                Python will make

General Principle