Python 如何解决 AttributeError:'list' 对象没有属性 'astype'?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46759801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:49:54  来源:igfitidea点击:

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

pythonnumpyattributes

提问by Tom

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

我只是想知道如何解决错误中的属性python3.6.错误是

'list' object has no attribute 'astype'.

“list”对象没有“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!

谢谢!

回答by

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.

根本问题是混淆了 Python 列表和 NumPy 数组,它们是不同的数据类型。np.foo(array)如果你给它们一个 Python 列表,通常调用的 NumPy 方法不会抱怨,它们会默默地将它转换为一个 NumPy 数组。但是,如果您尝试调用对象中包含的方法,array.foo()那么当然它必须已经具有适当的类型。

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 立即知道数组的类型。这避免了首先创建数组然后将其转换为另一种类型的不必要的工作。

NumPy recommends using dtype objectsinstead of strings like "float32".

NumPy 建议使用dtype 对象而不是像“float32”这样的字符串。