How to change values in matrix which matches to 1D array by python

Viewed 53

I just moved from MATLAB to python and spent 1day but couldn't solve this problem. Anyone has any thought on it? D1 is 1D array of 30 values= ['1','2',...'30'] D2 is 1D array of 30 values=['1','1',...'1'], later I might introduce different values in D2 as 1,1,2....3

I want to replace D1 values matching in matrix(Z1 of 512X512X50) by D2. I wrote following function but it doesn't work.

for i,n in enumerate(D1):
   for j in range(50):
        z1[:,:,j] = np.where(z1[:,:,j] == D1[i], D2[i], z[:,:,j])'''

On execution, get warning and output as follows.

$z1.max() output is 33 which should be 1.

warning: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison

1 Answers

Your description talks about 2 1d arrays and a 3d array. I've synthesised using smaller arrays. Beware of datatypes that Numpy generates - fixed length strings. I've used 2 characters everywhere for this example to work

I'm updating 3d array based on forming an array of tuples from np.where()

import numpy as np
D1 = ["0" + str(n+1) for n in range(9)]
D2 = [str(n) + "n" for n in range(9)]
Z1 = np.array([[["0" + str(k//3) for k in range(9)] for j in range(8)] for i in range(8)])

Z2 = Z1.copy()

for n in range(len(D1)):
    for x,y,z in list(zip(*np.where(Z1==D1[n]))):
        Z2[x][y][z] = D2[n]
{"D1":D1, "D2":D2, "Z1":Z1[0], "Z2":Z2[0]}


output (just first row of 3D array for sake of space)

{'D1': ['01', '02', '03', '04', '05', '06', '07', '08', '09'],
 'D2': ['0n', '1n', '2n', '3n', '4n', '5n', '6n', '7n', '8n'],
 'Z1': array([['00', '00', '00', '01', '01', '01', '02', '02', '02'],
        ['00', '00', '00', '01', '01', '01', '02', '02', '02'],
        ['00', '00', '00', '01', '01', '01', '02', '02', '02'],
        ['00', '00', '00', '01', '01', '01', '02', '02', '02'],
        ['00', '00', '00', '01', '01', '01', '02', '02', '02'],
        ['00', '00', '00', '01', '01', '01', '02', '02', '02'],
        ['00', '00', '00', '01', '01', '01', '02', '02', '02'],
        ['00', '00', '00', '01', '01', '01', '02', '02', '02']],
       dtype='<U2'),
 'Z2': array([['00', '00', '00', '0n', '0n', '0n', '1n', '1n', '1n'],
        ['00', '00', '00', '0n', '0n', '0n', '1n', '1n', '1n'],
        ['00', '00', '00', '0n', '0n', '0n', '1n', '1n', '1n'],
        ['00', '00', '00', '0n', '0n', '0n', '1n', '1n', '1n'],
        ['00', '00', '00', '0n', '0n', '0n', '1n', '1n', '1n'],
        ['00', '00', '00', '0n', '0n', '0n', '1n', '1n', '1n'],
        ['00', '00', '00', '0n', '0n', '0n', '1n', '1n', '1n'],
        ['00', '00', '00', '0n', '0n', '0n', '1n', '1n', '1n']],
       dtype='<U2')}
Related