Reputation: 135
In the code given below I am getting an error on the last line that list has attribute of reshape
cal should be a numpy array but cal.reshape is giving the error . Also while printing cal I am getting 13 element array but a 4 element array was expected which will be the sum of elements along the rows .
import numpy as np
A=np.array([[56.0,0.0,4.4,68.0],
[1.0,2.0,104.0,52.0,8.0],
[1.8,135.0,99.0,0.9]])
cal=A.sum(axis=0)
print(cal)
percentage=100*A/cal.reshape(1,4)
cal
should be a numpy array but cal.reshape
is giving the error . Also while printing cal
I am getting 13 element array but a 4 element array was expected which will be the sum of elements along the rows .
Upvotes: 0
Views: 154
Reputation: 20490
If you see carefully, your 2D list A
has 5 elements in the second row instead of 4 like the other rows, and that causes issues with np.sum
, since numpy assumes a homogeneous array where all sublists have equals rows.
So you would need to either remove an element from the 2nd list like so, (In below example I removed the first element) to make your array 3x4
import numpy as np
A=np.array([[56.0,0.0,4.4,68.0],
[2.0,104.0,52.0,8.0],
[1.8,135.0,99.0,0.9]])
cal=A.sum(axis=0)
print(cal)
percentage=100*A/cal
print(percentage)
And the output comes out as
[[93.64548495 0. 2.83140283 88.42652796]
[ 3.34448161 43.51464435 33.46203346 10.40312094]
[ 3.01003344 56.48535565 63.70656371 1.17035111]]
Or you can add extra 0's in the first and third row and reshape your array to (1,5)
import numpy as np
A=np.array([[56.0,0.0,4.4,68.0, 0],
[1.0, 2.0,104.0,52.0,8.0],
[1.8,135.0,99.0,0.9, 0]])
cal=A.sum(axis=0)
print(cal)
percentage=100*A/cal
print(percentage)
The output here will be
[[ 95.23809524 0. 2.12150434 56.24483044 0. ]
[ 1.70068027 1.45985401 50.14464802 43.01075269 100. ]
[ 3.06122449 98.54014599 47.73384764 0.74441687 0. ]]
Upvotes: 1
Reputation: 841
The problem is that the 2nd row has 5 elements instead of 4. If you correct this error your script will work.
Upvotes: 1