【发布时间】:2018-06-04 13:32:01
【问题描述】:
给定一个包含两种元素的 numpy 数组:
- “numpy.ndarray”条目和
- “NoneType”条目
如何将所有“NoneType”条目替换为例如np.zeros(some_shape)? 这是否也适用于任何类型的单个元素,例如标量而不是 NoneType?
例子:
test_array=
array([[array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8), ..., None, None,
None],
[array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8), ..., None, None,
None],
[array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8), ...,
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8), None, None],
...,
[array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8), ...,
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8), None],
[array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8), ...,
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8), None],
[array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8), ...,
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8)]], dtype=object)
test_array 中的数组可能如下所示:
test_array[323]=
array([array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8), None, None], dtype=object)
我想用与其他向量相同长度的零向量替换那些“无”条目(此处为位置 0 到 3)。 所以我对每个数组的结果(test_array 中的 test_array[i] 看起来像这样:
test_array[131]=
array([array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
array([[0, 0, 0, ..., 0, 0, 0]], dtype=uint8)], dtype=object)
所以我想用 np.zeros 数组填充所有 None 条目。确实存在 numpy 函数 np.nan_to_num 但这对我没有帮助,因为我需要类似“np.nan_to_array”的东西。
谢谢!
【问题讨论】:
标签: arrays numpy python-3.5 nonetype