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
Calculate sum for each column
> cal=A.sum(axis=0) #axis=0 vertically > print(cal)
Prints out
Then calculate percentages
> percentage=100*A/cal.reshape(1,4) > print(percentage)
Prints out
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
Python will auto expand 100 to a (1,4)
matrix of 100.
Python will make
Python will make