Python 序列的隐式转换可变长度列表到 NumPy 数组中导致数组的类型object.
v = [[1], [1, 2]]
np.array(v)
>>> array([[1], [1, 2]], dtype=object)
尝试强制另一种类型将导致异常:
np.array(v, dtype=np.int32)
ValueError: setting an array element with a sequence.
通过使用给定占位符填充“缺失”值来获取 int32 类型的密集 NumPy 数组的最有效方法是什么?
从我的样本序列来看v
,如果 0 是占位符,我想要得到这样的东西
array([[1, 0], [1, 2]], dtype=int32)
您可以使用itertools.zip_longest https://docs.python.org/3.4/library/itertools.html#itertools.zip_longest:
import itertools
np.array(list(itertools.zip_longest(*v, fillvalue=0))).T
Out:
array([[1, 0],
[1, 2]])
注意:对于Python 2,它是itertools.izip_longest https://docs.python.org/2/library/itertools.html#itertools.izip_longest.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)