How Do I Get The Address For An Element In A Python Array?
I'm a newbie and I'm trying to get the address of an element at a particular index in a Numpy or regular Python array. I'm following a class on Coursera where the instructor gets t
Solution 1:
An array and its attributes:
In [28]: arr = np.arange(1,8)
In [29]: arr.__array_interface__
Out[29]:
{'data': (41034176, False),
'strides': None,
'descr': [('', '<i8')],
'typestr': '<i8',
'shape': (7,),
'version': 3}
The data buffer location for a slice:
In[30]: arr[4:].__array_interface__['data'][0]Out[30]: 41034208In[31]: arr[4:].__array_interface__['data'][0]-arr.__array_interface__['data'][0]Out[31]: 32
The slice shares the data buffer, but with an offset of 4 elements (4*8).
Using this information I can fetch a slice using the ndarray
constructor (not usually needed):
In [35]: np.ndarray((3,), dtype=int, buffer=arr.data, offset=32)
Out[35]: array([5, 6, 7])
In [36]: arr[4:7]
Out[36]: array([5, 6, 7])
arr.data
is a memoryview
object that somehow references the data buffer of this array. The id/address of arr.data
is not the same as the data pointer I used above.
In [38]: arr.data
Out[38]: <memory at 0x7f996d950e88>
In [39]: type(arr.data)
Out[39]: memoryview
Note that data location for arr[4]
is totally different. It is 'unboxed', not a slice:
In [37]: arr[4].__array_interface__
Out[37]:
{'data': (38269024, False),
'strides': None,
'descr': [('', '<i8')],
'typestr': '<i8',
'shape': (),
'version': 3,
'__ref': array(5)}
Post a Comment for "How Do I Get The Address For An Element In A Python Array?"