I have a numpy array
[0 0 0 0 0 0 0 1 1 2 2 2 2 2 1 1 0 0 0 0 0 0 0 0]
which I want to convert/dissolve into
[[0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0]]
my current approach is to first use a while loop to split the array into just 1s and then create an array based on np.where(x>0). I however believe that this is not the most efficient and elegant numpy solution. any ideas on how to improve this?
source = np.array([0., 0., 0., 0., 0., 0., 0., 1., 1., 2., 2., 2., 2.,
2., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=np.int)
diss = None
while np.any(source):
row = np.greater(source, 0).astype(np.int)
if diss is None:
diss = row
else:
diss = np.vstack([diss, row])
source -= row
idx = np.where(diss > 0)
result = np.zeros((0,source.shape[0]), dtype=np.int)
for x, y in zip(*idx):
row = np.zeros(source.shape, dtype=np.int)
row[y] = 1
result = np.vstack([result, row])
source.max()?