2024-heraklion-data/exercises/.ipynb_checkpoints/view_or_copy-checkpoint.ipynb
2024-08-27 15:27:53 +03:00

8 KiB

In [107]:
import numpy as np


def is_view(a):
    return a.base is not None


def print_info(a):
    txt = f"""
Is it a view? {is_view(a)}

dtype\t{a.dtype}
ndim\t{a.ndim}
shape\t{a.shape}
strides\t{a.strides}
    """
    print(a)
    print(txt)


x = np.arange(12).reshape(3, 4).copy()
print_info(x)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Is it a view? False

dtype	int64
ndim	2
shape	(3, 4)
strides	(32, 8)
    
In [108]:
y = x[::2, :]
print_info(y)
[[ 0  1  2  3]
 [ 8  9 10 11]]

Is it a view? True

dtype	int64
ndim	2
shape	(2, 4)
strides	(64, 8)
    
In [109]:
y = x[1, :]
print_info(y)
[4 5 6 7]

Is it a view? True

dtype	int64
ndim	1
shape	(4,)
strides	(8,)
    
In [110]:
y = x[1]
print_info(y)
[4 5 6 7]

Is it a view? True

dtype	int64
ndim	1
shape	(4,)
strides	(8,)
    
In [111]:
y = x[[1, 2], [0, 3]]
print_info(y)
[ 4 11]

Is it a view? False

dtype	int64
ndim	1
shape	(2,)
strides	(8,)
    
In [112]:
# Get the first and third row
y = x[[0, 2], :]
print_info(y)
[[ 0  1  2  3]
 [ 8  9 10 11]]

Is it a view? False

dtype	int64
ndim	2
shape	(2, 4)
strides	(32, 8)
    
In [113]:
y = x + 2
print_info(y)
[[ 2  3  4  5]
 [ 6  7  8  9]
 [10 11 12 13]]

Is it a view? False

dtype	int64
ndim	2
shape	(3, 4)
strides	(32, 8)
    
In [114]:
y = x[[1, 2, 0], [1, 1, 2]]
print_info(y)
[5 9 2]

Is it a view? False

dtype	int64
ndim	1
shape	(3,)
strides	(8,)
    
In [115]:
y = x.reshape((6, 2))
print_info(y)
[[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]]

Is it a view? True

dtype	int64
ndim	2
shape	(6, 2)
strides	(16, 8)
    
In [116]:
y = x.T.reshape((6, 2))
print_info(y)
[[ 0  4]
 [ 8  1]
 [ 5  9]
 [ 2  6]
 [10  3]
 [ 7 11]]

Is it a view? True

dtype	int64
ndim	2
shape	(6, 2)
strides	(16, 8)
    
In [117]:
y = x.ravel()
print_info(y)
[ 0  1  2  3  4  5  6  7  8  9 10 11]

Is it a view? True

dtype	int64
ndim	1
shape	(12,)
strides	(8,)
    
In [118]:
y = x.T.ravel()
print_info(y)
[ 0  4  8  1  5  9  2  6 10  3  7 11]

Is it a view? False

dtype	int64
ndim	1
shape	(12,)
strides	(8,)
    
In [119]:
y = x[(x % 2) == 0]
print_info(y)
[ 0  2  4  6  8 10]

Is it a view? False

dtype	int64
ndim	1
shape	(6,)
strides	(8,)
    
In [120]:
y = np.sort(x, axis=1)
print_info(y)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Is it a view? False

dtype	int64
ndim	2
shape	(3, 4)
strides	(32, 8)
    
In [ ]:

In [ ]: