本文介绍了将 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 数组,填充缺失值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!