Home > Back-end >  Replacing one "0" in 2d array with "1"
Replacing one "0" in 2d array with "1"

Time:07-19

hi i want to replace a value in an array at a specific position with a "1" the index that is to be replaced is give by a random number calculator.

array: 
cellMAP_0 = np.full((11,7),0)

random number to be exchangend: 
start_point = random.randint(0,cellMAP_0.size)

fe. if star_point = 45, the index 45 in cellMAP_0 should be replaced with a 1 and cellMAP_0 should still be an 2d array

sry if this is very basic but i didnt found any help here with the search. thank you for your help

CodePudding user response:

You can use numpy.unravel_index to convert your 1D index into a ND one:

start_point = 45

cellMAP_0[np.unravel_index(45, cellMAP_0.shape)] = 1

output:

[[0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0]
 [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]
 [0 0 0 0 0 0 0]]

The order is LR, TD by default (C-order), if you want TD, LR (Fortran order), use order='F':

start_point = 45

cellMAP_0[np.unravel_index(45, cellMAP_0.shape, order='F')] = 1

output:

[[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 0 0 0 0 0 0]
 [0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0]]

CodePudding user response:

Another straightforward suggestion is this: This flattens the Array, then sets the number, then reshapes it into its original form.

import random

OriginalShape = (11,7)
cellMAP_0 = np.full(OriginalShape,0).flatten()

start_point = random.randint(0,cellMAP_0.size)
cellMAP_0[start_point] = 1.

cellMAP_0=cellMAP_0.reshape(OriginalShape)

print(cellMAP_0)
print(start_point)
  • Related