Skip to content Skip to sidebar Skip to footer

How Come Not-copying A Numpy Array Changes The Data Attribute?

As my MWE below shows, calling np.array(a, copy=False) on an existing array a returns something that behaves exactly as expected, except that the .data attributes seem to differ. H

Solution 1:

If you type:

help(a.data)

You will see that it does not return exactly what you expect:

classmemoryview(object)
 |  memoryview(object)
 |  
 |  Create a new memoryviewobject which references the given object.
 |  
 |  Methods defined here:
 |  

It creates a memoryview that references that object. If you want the memory address use id:

id(a) == id(b)
True

Note that:

id(a) isid(b)
False

Because id(a) returns an integer and id(b) too and their memory address isn't the same although their values are.

If you want hexadecimal memory:

hex(id(a))

Also, from NumPy doc: numpy.ndarray.data (I really don't know why this .data is useful but it exists)

Solution 2:

In [33]: a = np.array([2])                                                                             
In [34]: b = np.array(a, copy=False)  

A nice human-readable way of checking for shared data buffer is the __array_interface__ dictionary.

In [36]: a.__array_interface__                                                                         
Out[36]: 
{'data': (69508768, False),
 'strides': None,
 'descr': [('', '<i8')],
 'typestr': '<i8',
 'shape': (1,),
 'version': 3}
In [37]: b.__array_interface__                                                                         
Out[37]: 
{'data': (69508768, False),
 'strides': None,
 'descr': [('', '<i8')],
 'typestr': '<i8',
 'shape': (1,),
 'version': 3}

a.data can be used to make a new array, but otherwise isn't very useful. And even this use is too low-level for most purposes:

In [44]: c = np.ndarray(shape=(1,1), dtype=int, buffer=a.data)                                         
In [45]: c                                                                                             
Out[45]: array([[2]])
In [46]: c.__array_interface__                                                                         
Out[46]: 
{'data': (69508768, False),
 'strides': None,
 'descr': [('', '<i8')],
 'typestr': '<i8',
 'shape': (1, 1),
 'version': 3}

Post a Comment for "How Come Not-copying A Numpy Array Changes The Data Attribute?"