One way to visualize whether two arrays can share memory is to look at their 'ravel'
In [422]: x = np.arange(24).reshape((4,3,2))
In [423]: x
Out[423]:
array([[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 6, 7],
[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15],
[16, 17]],
[[18, 19],
[20, 21],
[22, 23]]])
In [424]: y = x[[1,3,0,2],:,:] # rearrange the 1st axis
In [425]: y
Out[425]:
array([[[ 6, 7],
[ 8, 9],
[10, 11]],
[[18, 19],
[20, 21],
[22, 23]],
[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[12, 13],
[14, 15],
[16, 17]]])
In [428]: x.ravel(order='K')
Out[428]:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23])
In [429]: y.ravel(order='K')
Out[429]:
array([ 6, 7, 8, 9, 10, 11, 18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4,
5, 12, 13, 14, 15, 16, 17])
Notice how the elements in y
occur in a different order. There's no way that we can 'stride' through x
to get y
.
With out the order
parameter, ravel use 'C', which can confuse us when the new array does some sort of axis transpose. As noted in the other answer x.T
is a view, achieved by reordering the axes, and hence changing the strides.
In [430]: x.T.ravel() # transposed array viewed row by row
Out[430]:
array([ 0, 6, 12, 18, 2, 8, 14, 20, 4, 10, 16, 22, 1, 7, 13, 19, 3,
9, 15, 21, 5, 11, 17, 23])
In [431]: x.T.ravel(order='K') # transposed array viewed column by column
Out[431]:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23])
__array_interface__
is a handy tool for looking at the underlying structure of an array:
In [432]: x.__array_interface__
Out[432]:
{'data': (45848336, False),
'strides': None,
'descr': [('', '<i8')],
'typestr': '<i8',
'shape': (4, 3, 2),
'version': 3}
In [433]: y.__array_interface__
Out[433]:
{'data': (45892944, False),
'strides': None,
'descr': [('', '<i8')],
'typestr': '<i8',
'shape': (4, 3, 2),
'version': 3}
In [434]: x.T.__array_interface__
Out[434]:
{'data': (45848336, False), # same as for x
'strides': (8, 16, 48), # reordered strides
'descr': [('', '<i8')],
'typestr': '<i8',
'shape': (2, 3, 4),
'version': 3}