Reputation: 3257
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])
Upvotes: 1
Views: 392
Reputation: 13387
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])
Upvotes: 1
Reputation: 48367
You could use list comprehension version of your solution.
desired_result = np.array([el[:,:,0] for el in arr])
Upvotes: 1