Suppose I have this list.
randz = [1.59,2.51,1.73,[0.61, 0.38],2.67,0]
When counting the number of positions of randz list, then I get
count = [1,1,1,2,1,1]
As you can see, I want to bring randz list to substitute in position 1
of the below binary array based on row.
zr = np.array([[1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
My target is like:
newzr = np.array([[1.59, 0, 0, 0, 0, 0],
[0, 0, 0, 2.51, 0, 0],
[0, 0, 1.73, 0, 0, 0],
[0, 0.61 or 0.38, 0, 0, 0.38 or 0.61, 0],
[2.67, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
However, I struk on the fourth row (value >1) that I need to substitute [0.61, 0.38] in column 2 and 5 or column 5 and 2.
My current coding is broken when counting greater 1:
zenext=[]
for i in range(len(randz)):
if count[i] == 1:
zenext.append(randz[i]*zr[i])
if count[i] > 1:
...........
Would you recommend what I could do? Thank you very much.
To achieve the desired result, you can modify the code as follows:
import numpy as np
randz = [1.59, 2.51, 1.73, [0.61, 0.38], 2.67, 0]
count = [1, 1, 1, 2, 1, 1]
zr = np.array([[1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
zenext = []
for i in range(len(randz)):
if count[i] == 1:
zenext.append(randz[i] * zr[i])
elif count[i] > 1:
indices = np.where(zr[i] == 1)[0]
values = np.array(randz[i])
zenext.append(np.zeros_like(zr[i]))
zenext[-1][indices] = values
newzr = np.array(zenext)
print(newzr)
This code checks if count[i] is greater than 1, and if so, it retrieves the indices where zr[i] is equal to 1. Then, it creates an array of zeros with the same shape as zr[i] and assigns the corresponding values from randz[i] to the retrieved indices. The resulting array is appended to the zenext list.
Finally, zenext is converted into a NumPy array newzr, which will have the desired values substituted based on the conditions you specified.
Note that the code assumes that the lengths of randz and count are the same and match the number of rows in zr.