From 92f9f42b6d5f0d611b4f97cad27b824ade5b1fd8 Mon Sep 17 00:00:00 2001 From: David Rotermund <54365609+davrot@users.noreply.github.com> Date: Tue, 19 Dec 2023 10:41:04 +0100 Subject: [PATCH] Update README.md Signed-off-by: David Rotermund <54365609+davrot@users.noreply.github.com> --- numpy/dimensions/README.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/numpy/dimensions/README.md b/numpy/dimensions/README.md index ae52c4f..75585dc 100644 --- a/numpy/dimensions/README.md +++ b/numpy/dimensions/README.md @@ -96,3 +96,30 @@ print(type(np.array(z))) # -> print(type(z)) # -> print(z.shape) # -> AttributeError: 'int' object has no attribute 'shape' ``` + +## Stop vanishing dimensions + +One way to do stop vanishing dimensions is to use slices of thickness 1. If you want the nth element, then use **n:n+1**: + +```python +import numpy as np + +data = np.zeros((5, 3, 2)) + +# All the same dimensionwise +print(data.shape) # -> (5, 3, 2) + +print(data[0:1, :, :].shape) # -> (1, 3, 2) +print(data[:, 0:1, :].shape) # -> (5, 1, 2) +print(data[:, :, 0:1].shape) # -> (5, 3, 1) + +print(data[:, 0:1, 0:1].shape) # -> (5, 1, 1) +print(data[0:1, :, 0:1].shape) # -> (1, 3, 1) +print(data[0:1, 0:1, :].shape) # -> (1, 1, 2) + +print(data[0:1, 0:1, 0:1].shape) # -> (1, 1, 1) +print(type(data[0:1, 0:1, 0:1])) # -> +``` + +**Please understand this creates a view which is connected to original data.** If necessary make a **copy()**. +