'How to make one element in a numpy array share the same memory address with another element in a different numpy array?
Is it possible to make one element in a numpy array share the same memory address with another element in a different numpy array, so that if I change one, the other element in the other numpy array changes?
a = np.random.uniform(0, 1, 4) #[0.2, 0.5, 0.6, 0.3]
b = np.random.uniform(0, 1, 4) #[0.4, 0.7, 0.8, 0.1]
#let b[0] = a[0]
b[0] = a[0] # b[0] = 0.2 and a[0] = 0.2
If I change b[0], I want a[0] to also change. How do I do that?
Solution 1:[1]
Technically, yes, although it's not practical to do so. Here is an example:
buffer = np.zeros((5, 7))
a = buffer[::2, ::3]
b = buffer[1:4, 3:6]
By adjusting the strides of a to step around b, you've created a pair of arrays such that a[1, 1] is at the same memory address as b[1, 0], but none of the other elements are shared between then.
This wastes a lot of memory and slows things down, since the arrays can't be contiguous in the general case.
The example you added to the question is simpler to handle:
buffer = np.random.uniform(0, 1, 7)
a = buffer[4::-1]
b = buffer[4:]
The wasteful approach to the same would be
buffer = np.empty(15)
a = buffer[:4]
b = buffer[::4]
a[:] = np.random.uniform(0, 1, 4)
b[:] = np.random.uniform(0, 1, 4)
In general though, I'd recommend using a property on an array subclass or something like that.
Solution 2:[2]
import numpy as np
arr =np.array([1,2,3,4,5])
int_arr1 = arr.astype(int)
for i in range(len(int_arr1)):
print("The Element", int_arr1[i] , " Memory Location :",int_arr1[i].data)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Rahul Yadav |
