Numpy Array Memory

I have a question about numpys memory representations:

Suppose we have two arrays with memory:

import numpy as np
import gc
x = np.arange(4*3).reshape(4,3).astype(float)
y = (np.arange(5) - 5).astype(float)
y_ref = y

We use these ( x, y) in the structure, so we can’t just redefine them, as the user could link them for himself (as in y_ref). Now we want to combine their memory in one view. So, that the only kind, say p, divides memory into both arrays.

I did it as follows, but I don't know if this causes a memory leak:

p = np.empty(x.size+y.size, dtype=float) # create new memory block with right size
c = 0 # current point in memory

# x
p[c:c+x.size].flat = x.flat # set the memory for combined array p
x.data = p[c:c+x.size].data # now set the buffer of x to be the right length buffer of p

c += x.size

# y
p[c:c+y.size].flat = y.flat # set the memory for combined array p
y.data = p[c:c+y.size].data # and set the buffer of x to be the right length buffer of p

Thus, now we can work with a single view por with any of the arrays, without redoing each link to them

x[3] = 10
print p[3*3:4*3]
# [ 10.  10.  10.]

Even y_refgot an update:

print y[0] # -5
y_ref[0] = 100
print p[x.size] # 100

Is this the correct way to set array memory as a view to another array?

, ?

, x y, . ?

@Jaime:

p.size ( ) , (). , , . , .

, , , python .

+4
1

, .

https://github.com/numpy/numpy/blob/6c6ddaf62e0556919a57d510e13ccb2e6cd6e043/numpy/core/src/multiarray/getset.c#L329

, :

import numpy as np

a = np.zeros(10)
b = np.zeros(10)
c = a[:]
a.data = b
print c
+3

Source: https://habr.com/ru/post/1540496/


All Articles