用其他元素替换NumPy数组元素

时间:2019-05-29 10:31:31

标签: python arrays numpy

假设我有一个随机生成的3d数组srouceArray

ex: np.random.rand(3, 3, 3)

array([[[0.61961383, 0.26927599, 0.03847151],
        [0.03497162, 0.77748313, 0.15807293],
        [0.15108821, 0.36729448, 0.19007034]],

      [[0.67734758, 0.88312758, 0.97610746],
       [0.5643174 , 0.20660141, 0.58836553],
       [0.59084109, 0.77019768, 0.35961768]],

      [[0.19352397, 0.47284641, 0.97912889],
       [0.48519117, 0.37189048, 0.37113941],
       [0.94934848, 0.92755083, 0.52662299]]])

我想将所有第3维元素随机替换为零。

预期数组:

array([[[0, 0, 0],
        [0.03497162, 0.77748313, 0.15807293],
        [0.15108821, 0.36729448, 0.19007034]],

      [[0.67734758, 0.88312758, 0.97610746],
       [0 , 0, 0],
       [0.59084109, 0.77019768, 0.35961768]],

      [[0, 0, 0],
       [0, 0, 0],
       [0.94934848, 0.92755083, 0.52662299]]])

我正在考虑生成“蒙版”吗?使用random

np.random.choice([True, False], sourceArray.shape, p=[...])

并以某种方式将其转换为False=[0, 0, 0]True=[1, 1, 1]的3d数组并与源相乘...

但是我不知道如何实现这种转变。我敢打赌,有一种我不知道的简单方法。

3 个答案:

答案 0 :(得分:1)

如果我正确理解了数据结构,可以使用它(这将更改原始数组):

import numpy as np

l = np.random.rand(5, 4, 3)
m = np.random.choice([True, False], size=(l.shape[0], l.shape[1]))
l[m] = [0, 0, 0]
l
array([[[0.62551611, 0.26268253, 0.51863006],
        [0.        , 0.        , 0.        ],
        [0.45038189, 0.97229114, 0.63736078],
        [0.        , 0.        , 0.        ]],

       [[0.54282399, 0.14585025, 0.80753245],
        [0.        , 0.        , 0.        ],
        [0.        , 0.        , 0.        ],
        [0.18190234, 0.19806439, 0.3052623 ]],

       [[0.        , 0.        , 0.        ],
        [0.46409806, 0.39734112, 0.21864433],
        [0.        , 0.        , 0.        ],
        [0.65046231, 0.78573179, 0.76362864]],

       [[0.05296007, 0.50762852, 0.18839052],
        [0.52568072, 0.8271628 , 0.24588153],
        [0.92039708, 0.8653368 , 0.96737845],
        [0.        , 0.        , 0.        ]],

       [[0.        , 0.        , 0.        ],
        [0.37039626, 0.64673356, 0.01186108],
        [0.        , 0.        , 0.        ],
        [0.        , 0.        , 0.        ]]])

答案 1 :(得分:1)

从数学上讲,它可以生成另一个随机的0-1数组,乘以原始数组:

import numpy as np

ar = np.random.rand(3,3,3)
ar2 = np.random.randint(2, size = (3,3,1))
ar3 = ar*ar2

答案 2 :(得分:0)

您可以这样做:

a = np.ones((3, 3, 3)) # your original array
b = a.reshape((-1,3)) # array of just rows from 3rd dim
temp = np.random.random(b.shape[0]) # get random value from 0 to 1 for each row from b
prob = 0.4 # up to you - probability of making a row all zeros
mask = temp<prob
b[mask]=0
result = b.reshape(a.shape) # getting back to original shape

示例输出:

[[[0. 0. 0.]
  [1. 1. 1.]
  [1. 1. 1.]]

 [[1. 1. 1.]
  [1. 1. 1.]
  [0. 0. 0.]]

 [[0. 0. 0.]
  [1. 1. 1.]
  [0. 0. 0.]]]