将Python序列转换为NumPy数组,填充缺失值 [英] Convert Python sequence to NumPy array, filling missing values
本文介绍了将Python序列转换为NumPy数组,填充缺失值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将可变长度列表的Python序列隐式转换为NumPy数组会导致该数组的类型为 object .
The implicit conversion of a Python sequence of variable-length lists into a NumPy array cause the array to be of type object.
v = [[1], [1, 2]]
np.array(v)
>>> array([[1], [1, 2]], dtype=object)
尝试强制使用其他类型会导致异常:
Trying to force another type will cause an exception:
np.array(v, dtype=np.int32)
ValueError: setting an array element with a sequence.
通过使用给定的占位符填充缺失"值来获取类型为int32的密集NumPy数组的最有效方法是什么?
What is the most efficient way to get a dense NumPy array of type int32, by filling the "missing" values with a given placeholder?
从我的示例序列v
,如果占位符为0,我想得到类似的东西
From my sample sequence v
, I would like to get something like this, if 0 is the placeholder
array([[1, 0], [1, 2]], dtype=int32)
推荐答案
您可以使用 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 .
Note: For Python 2, it is itertools.izip_longest.
这篇关于将Python序列转换为NumPy数组,填充缺失值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文