Numpy Swap/Substitute NoneType 条目与 Numpy 数组(即向量)

Numpy Swap/Substitute NoneType Entry with Numpy Array (i.e. vector)

给定一个包含两种类型元素的 numpy 数组:

  1. "numpy.ndarray" 个条目和
  2. "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)长度相同的零向量替换那些 "None" 条目。 这样我对每个数组的结果(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".

这样的东西

谢谢!

通常我不会在 NumPy 中使用 for 循环,但在你的情况下你有一个对象数组,它无论如何都不是很有效,并且处理 None 和 sub-存储为对象的数组非常棘手。所以,保持简单:

prototype = a[0]
for i, x in enumerate(a):
    if x is None:
        a[i] = np.zeros_like(prototype)

如果 a[0] 是 None,您当然需要找到一个 prototype。这留作练习。