How to solve the AttributeError:'list' object has no attribute 'astype'?

我是研究僧i 提交于 2021-01-21 12:15:37

问题


I am just wondering how to solve the attribute error in python3.6. The error is

'list' object has no attribute 'astype'.

My related code is as blow.

def _init_mean_std(self, data):
    data = data.astype('float32')
    self.mean, self.std = np.mean(data), np.std(data)
    self.save_meanstd()
    return data

Is there anyone who can advice to me?

Thank you!


回答1:


The root issue is confusion of Python lists and NumPy arrays, which are different data types. NumPy methods that are invoked as np.foo(array) usually won't complain if you give them a Python list, they will convert it to an NumPy array silently. But if you try to invoke a method contained in the object, like array.foo() then of course it has to have the appropriate type already.

I would suggest using

data = np.array(data, dtype=np.float32)

so that the type of an array is known to NumPy at once. This avoids unnecessary work where you first create an array and then cast it to another type.

NumPy recommends using dtype objects instead of strings like "float32".



来源:https://stackoverflow.com/questions/46759801/how-to-solve-the-attributeerrorlist-object-has-no-attribute-astype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!