Morten Lind
Morten Lind

Reputation: 103

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)
b.set_data_reference(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.

Upvotes: 1

Views: 247

Answers (3)

Nils Werner
Nils Werner

Reputation: 36765

Usually when functions are not always supposed to create their own buffer they implement an interface like

def func(a, b, c, out=None):
    if out is None:
        out = numpy.array(x, y)
    # ...
    return out

that way the caller can control if an existing buffer is used or not.

Upvotes: 0

user2357112
user2357112

Reputation: 280973

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.

Upvotes: 1

Francesco Nazzaro
Francesco Nazzaro

Reputation: 2916

Every variable in python is a pointer so you can use directly = as follow

import numpy as np

a = np.array([1,2,3])
b = a

You can check that b refers to a as follow

assert a[1] == b[1]
a[1] = 4
assert a[1] == b[1]

Upvotes: 0

Related Questions