Morten Lind Morten Lind - 1 year ago 45
Python Question

In NumPy, how do I set array b's data to reference the data of array a?

Say I have ndarray a and b of compatible type and shape. I now wish for the data of b to be referring to the data of a. That is, without changing the array b object itself or creating a new one. (Imagine that b is actually an object of a class derived from ndarray and I wish to set its data reference after construction.) In the following example, how do I perform the b.set_data_reference?

import numpy as np
a = np.array([1,2,3])
b = np.empty_like(a)

This would result in b[0] == 1, and setting operations in one array would affect the other array. E.g. if we set a[1] = 22 then we can inspect that b[1] == 22.

N.B.: In case I controlled the creation of array b, I am aware that I could have created it like

b = np.array(a, copy=True)

This is, however, not the case.

Answer Source

NumPy does not support this operation. If you controlled the creation of b, you might be able to create it in such a way that it uses a's data buffer, but after b is created, you can't swap its buffer out for a's.