1

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.

1
  • 1
    could you provide a small sample of the a and b array to save people having to create their own examples which may not be appropriate to your case. Commented Sep 12, 2016 at 8:58

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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]

1 Comment

You are letting the identifier point to the object underlying a. That is not the same as having the data of b refer to the data of a. Imagine b is a given object of another class, which inherits from ndarray.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.