1

I have a numpy array arr of numpy arrays each with varying length. I can get the shape of arr:

arr.shape

>>> (9,) 

I can get the shape of one of the elements of arr:

arr[0].shape

>>> (6, 1, 2)

And I know that all such elements have shape (n, 1, 2).

I want to slice arr to get a 1 dimensional result as follows:

arr[:,:,:,0]

But I get the following error:

IndexError: too many indices for array

EDIT: My original question was misleading. I want to do this slice so that I can assign values to the slice. So getting the slice in a new variable is not useful for my case. Essentially I want to do something like this in a simple one liner:

arr[:,:,:,0] = arr[:,:,:,0] - np.min(arr[:,:,:,0])
1
  • The element arrays have to be operated on individually. It is basically a list of arrays. Commented Jan 26, 2020 at 14:37

2 Answers 2

1

You can fix your first (in fact all varying ones) dimension, and apply your transformation per static-shaped elements of arr

import numpy as np
from random import randint

arr=np.array([np.random.randint(3,15, size=(randint(3,9),randint(3,7),randint(6,19))) for el in range(9)])

print(arr.shape)
print(arr[0].shape)
for i in range(arr.shape[0]):
    arr[i][:,:,0]-=arr[i][:,:,0].min()
    print(arr[i][:,:,0])
Sign up to request clarification or add additional context in comments.

Comments

1

You could use list comprehension version of your solution.

desired_result = np.array([el[:,:,0] for el in arr])

1 Comment

Thank you. Although I made a mistake with the way I asked the question and now I've reframed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.