1

Basically I want to simply a function like this:

arr = np.array([[0.2, 0.4], [-0.9, -0.8]])

def take_dimension(arr, dim=None):
    """dim is either None, 0 or 1"""
    
    # return array with specific dimension
    if dim is not None:
        return arr[dim, :]
    
    # return array unaltered
    return arr
    
print(take_dimension(arr))  # returns full array:
# [[ 0.2  0.4]
#  [-0.9 -0.8]]
print(take_dimension(arr, 0))  # returns: [0.2 0.4]
print(take_dimension(arr, 1))  # returns: [-0.9 -0.8]

Tried

Counter to my expectations, return arr[None, :] does not return arr as-is, but instead adds a dimension (arr[None, :].shape outputs (1, 2, 2)).

Question

Is there a value I can assign to dim, so that it returns the full array (effectively functioning as :)? Then I could simplify the code to:

# not working
def take_dimension(arr, dim=':'):
    return arr[dim, :]

print(take_dimension(arr))
# IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
NumesSanguis
  • 5,832
  • 6
  • 41
  • 76
  • 1
    Use `slice(None)`. – jdehesa Jun 24 '20 at 09:23
  • slice(None) works, thank you! However, why does it work? If I check the output of `print(slice(None))`, it prints: `slice(None, None, None)`. – NumesSanguis Jun 24 '20 at 09:26
  • 2
    something regarding your question/code formulation: what you did is **not** selecting a *dimension* but selecting a *row* index of your input. You cannot select a *dimension* in that way, because a *dimension* is *either* **row** or **column** in your case, not a specific row or column. – Dorian Jun 24 '20 at 09:57
  • 1
    @NumesSanguis [`slice`](https://docs.python.org/3/library/functions.html#slice) is the value representation of the `:` indexing syntax. In general, `slice(a, b, c)` is the same as `a:b:c`, and `:` is equivalent to `None:None:None`, so `slice(None)` (equal to `slice(None, None, None)`) is the same as `:`. `slice` objects are immutable too, so you can safely use it as default value for a parameter. – jdehesa Jun 24 '20 at 10:04
  • 1
    The interpreter translates syntactic structures into objects and method calls. `[]` indexing becomes a `__getitem__` method call. `a:b:c` becomes a `slice(a,b,c)` object. Multidimensional indexing is a tuple. – hpaulj Jun 24 '20 at 15:36
  • 1
    You were wondering why `None` adds a new axis? That's because under the hood, `np.newaxis` is just a `None`. So in "numpy-language", you were accidentally asking for a new axis! You can confirm it by running: `None is np.newaxis` and you should get a `True` – imochoa Jun 25 '20 at 09:37

0 Answers0