I've been following a video tutorial on python, and I received an attribute error regardless typing the exact same code as the video.
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]])
cal = A.sum(axis=0)
percentage = 100*A/cal.reshape(1,4)
print(percentage)
The attribute error points to the percentage variable, stating that the list has no attribute 'reshape'. I searched for solutions and saw on the documentation that it has been "Deprecated since version 0.19.0. Calling this method will raise an error. Please call .values.reshape(...) instead.", and I tried the updated one according to what the documentation had provided.
percentage = 100*A/cal.values.reshape(1,4)
After this attempt, it still led to an attribute error. I don't know if I did it wrong because I'm completely new to python. Some help would be appreciated.
CodePudding user response:
I got this warning:
VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray. A = np.array([[56.0, 0.0, 4,4, 68.0],
And according to this question: numpy.VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences
This has to do with the creation of arrays from lists of unequal length. So I presume that in this line:
[56.0, 0.0, 4,4, 68.0]
The 4,4 should have been a 4.4, right?
CodePudding user response:
You first list has one more item (5 vs 4 for the others). This makes it an object
array with python lists as elements (and you get a VisibleDeprecationWarning
warning).
Thus cal becomes a concatenation of the lists ([56.0, 0.0, 4, 4, 68.0, 1.2, 104.0, 52.0, 8.0, 1.8, 135.0, 99.0, 0.9]
) instead of a numpy array, triggering your error.
I imagine this might be a typo and changing 4,4
to 4.4
gives the following output:
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],])
cal = A.sum(axis=0)
# array([ 59. , 239. , 155.4, 76.9])
percentage = 100*A/cal.reshape(1,4)
print(percentage)
output:
[[94.91525424 0. 2.83140283 88.42652796]
[ 2.03389831 43.51464435 33.46203346 10.40312094]
[ 3.05084746 56.48535565 63.70656371 1.17035111]]