Python 将列表转换为 numpy 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26850355/
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 01:04:28  来源:igfitidea点击:

Converting list to numpy array

pythonnumpyscikit-learn

提问by Priya Narayanan

I have managed to load images in a folder using the command line sklearn: load_sample_images()

我设法使用命令行 sklearn 在文件夹中加载图像: load_sample_images()

I would now like to convert it to a numpy.ndarrayformat with float32datatype

我现在想将其转换为numpy.ndarray具有float32数据类型的格式

I was able to convert it to np.ndarrayusing : np.array(X), however np.array(X, dtype=np.float32)and np.asarray(X).astype('float32')give me the error:

我能够将其转换为np.ndarrayusing : np.array(X),但是np.array(X, dtype=np.float32)np.asarray(X).astype('float32')给我错误:

ValueError: setting an array element with a sequence.
ValueError: setting an array element with a sequence.

Is there a way to work around this?

有没有办法解决这个问题?

from sklearn_theano.datasets import load_sample_images
import numpy as np  

kinect_images = load_sample_images()
X = kinect_images.images

X_new = np.array(X)  # works
X_new = np.array(X[1], dtype=np.float32)  # works

X_new = np.array(X, dtype=np.float32)  # does not work

回答by Thom Ives

If you have a list of lists, you only needed to use ...

如果你有一个列表列表,你只需要使用 ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINKin the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

根据scipy / numpy 文档中的此链接。您只需要在对 asarray 的调用中定义 dtype。