I have a numpy array and depending on the value from another array, I would like to either update the value of the row, or delete it, or add one.
Example:
I have arr, the one with all values and to keep updated with value from new_arr. If a value in the first column of new_arr exists in arr, then the second column of arr is updated. If the value does no exist, then add a new row. If the second column in new_arr == 0, then delete the row in arr with the matching first column.
arr = np.array([[1, 10],
[2, 15],
[3, 5],
[4, 10]])
new_arr = np.array([[2, 20], # 2 exists in arr and 20 > 0 --> update in arr
[5, 20], # 5 does not exists in arr --> add row in arr
[1, 0]]) # 1 exists in arr but col 2 == 0--> delete row in arr
Then I would like to obtain:
arr = np.array([[2, 20],
[3, 5],
[4, 10],
[5, 20]])
Observe that arr is ordered by the first column. Also arr has a maximum lenght of 1000 rows.
Any simple and fast method please?
Initially arr and new_arr are lists. I've turned them into numpy arrays. However, as I do not do any strong calculation with arr, most likely it would be faster to keep it as a list.
Keeping the input arrays as numpy constructs, here's how I would do it.
def process_arrays(np1, np2):
np1d = dict((np1[x][0], np1[x][1]) for x in range(len(np1)))
np2d = dict((np2[x][0], np2[x][1]) for x in range(len(np2)))
for ky2 in np2d.keys():
if ky2 in np1d.keys():
if np2d[ky2] == 0:
del np1d[ky2]
else:
np1d[ky2] = np2d[ky2]
else:
np1d[ky2] = np2d[ky2]
return np.array(np1d)
Given you input executing:
process_arrays(arr, newArr)
Yields:
array({2: 20, 3: 5, 4: 10, 5: 20}, dtype=object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With