0

Both transpose and ravel give the view of the original array. But combined together I got a new array?

Say I create an Numpy array, a = np.arange(10).reshape(2,5)

In [13]: a = np.arange(10).reshape(2,5)
In [14]: a
Out[14]:
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

I transpose it:

In [15]: b = a.T
In [16]: b
Out[16]:
array([[0, 5],
       [1, 6],
       [2, 7],
       [3, 8],
       [4, 9]])

I can check b is a view of a, currently it is fine. Then I do b.ravel()

In [17]: c = b.ravel()
In [18]: c
Out[18]: array([0, 5, 1, 6, 2, 7, 3, 8, 4, 9])

Now python tells me c is no longer a view of b or a. This can be checked by np.may_share_memory(b, c), or by editing elements in b:

In [19]: np.may_share_memory(b, c)
Out[19]: False

In [20]: b[1,0] = 100
In [21]: print(b)
    ...: print(a)
    ...: print(c)
[[  0   5]
 [100   6]
 [  2   7]
 [  3   8]
 [  4   9]]
[[  0 100   2   3   4]
 [  5   6   7   8   9]]
[0 5 1 6 2 7 3 8 4 9]

So, what is happening here? Though every step (transpose, ravel) is a view of the original array, combined together I got a new array?

Jinchen
  • 1
  • 1
  • 2
    From the reshape docs: " It is not always possible to change the shape of an array without copying the data". Ravel is a form of reshape. `c` cannot be produced by just changing the shape and strides of `a`. – hpaulj May 13 '20 at 15:59
  • @hpaulj Thank you for your comment. That makes sense! – Jinchen May 13 '20 at 16:05
  • I noticed a good explanation of this reshape issue by @hpaulj in the post https://stackoverflow.com/questions/36995289/when-will-numpy-copy-the-array-when-using-reshape#comment61544731_36995289 – Jinchen May 13 '20 at 16:52

0 Answers0