array manipulation - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: array manipulation (/thread-34813.html) |
array manipulation - divon - Sep-02-2021 Hello everyone, I have question about array manipulation in Numpy. In this case I have 3 arrays: arr_1 = [ 0 1 2 4 8 3 5 9 6 10 12 7 11 13 14 15] arr_2 = [1 0 0 1 1 1 0 1] arr_3 = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] I would like to replace the value of arr_3 with arr_2 based on condition arr_1 (from position of element 9 to 16). For example: arr_1 element 8 = 6 then arr_3 element 6 = 0 will replaced by arr_2 element 0 = 1 (I am counting the position of element starting from 0 which is the same as program counting the element of array). arr_1 element 9 = 10 then arr_3 element 10 = 0 will replaced by arr_2 element 1 = 0 arr_1 element 10 = 12 then arr_3 element 12 = 0 will replaced by arr_2 element 2 = 0 arr_1 element 11 = 7 then arr_3 element 7 = 0 will replaced by arr_2 element 3 = 1 arr_1 element 12 = 11 then arr_3 element 11 = 0 will replaced by arr_2 element 4 = 1 arr_1 element 13 = 13 then arr_3 element 13 = 0 will replaced by arr_2 element 5 = 1 arr_1 element 14 = 14 then arr_3 element 14 = 0 will replaced by arr_2 element 6 = 0 arr_1 element 15 = 15 then arr_3 element 15 = 0 will replaced by arr_2 element 7 = 1 After the operation is complete, the value of arr_3 will be: arr_3 = [0 0 0 0 0 0 1 1 0 0 0 1 0 1 0 1] The code that I have written so far: import numpy as np arr_1 = np.array([0, 1, 2, 4, 8, 3, 5, 9, 6, 10, 12, 7, 11, 13, 14, 15]) arr_2 = np.array([1, 0, 0, 1, 1, 1, 0, 1]) arr_3 = np.zeros((16), dtype=int)Since I am stuck on this replacement thing, I can't move to the next step. RE: array manipulation - deanhystad - Sep-03-2021 This is pretty easy if you ignore the first 8 elements of arr_1. arr_1[8:] are the indices where arr_2 values should be placed in arr_3. import numpy as np arr_1 = np.array([0, 1, 2, 4, 8, 3, 5, 9, 6, 10, 12, 7, 11, 13, 14, 15]) arr_2 = np.array([1, 0, 0, 1, 1, 1, 0, 1]) arr_3 = np.zeros((16), dtype=int) for index, value in zip(arr_1[8:], arr_2): arr_3[index] = value print(arr_3) RE: array manipulation - naughtyCat - Sep-03-2021 arr1 = [0, 1, 2, 4, 8, 3, 5, 9, 6, 10, 12, 7, 11, 13, 14, 15] arr2 = [1, 0, 0, 1, 1, 1, 0, 1] arr3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] x = len(arr1)-len(arr2) for n, i in enumerate(arr1[x:]): if arr2[n]: arr3[i] = arr2[n] print(*arr3) RE: array manipulation - divon - Sep-03-2021 Thank you very much for your reply, @deanhystad, and @naughtyCat Both of your replies are working perfectly, and I can continue with my work. Once again, Thank you very much. |