Reputation: 19
I have the following problem:
x = np.arange(9).reshape((1,3,3))
x
which leads me to a multidimensional array with 3 elements:
array([[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]])
How can I create a new array with just the first two elements out of each dimension? So that it looks like this output:
array([[[0, 1],
[3, 4],
[6, 7]]])
Upvotes: 1
Views: 1351
Reputation: 3856
This is just list slicing!
list[a:b]
>> start from a-th element and go up to b-th element
import numpy as np
x = np.arange(9).reshape((1,3,3))
def my_slicing (inp, shape):
inp = list(inp)
if type(shape) is tuple: shape=list(shape)
if len(shape)>1:
for i,v in enumerate(inp[:shape[0]]):
inp[i]=my_resize(v,shape[1:])
else:
return inp[:shape[0]]
return np.array(inp[:shape[0]])
pass
print(x)
print(my_slicing(x, (1,3,2))) # custom slicing function
print(x[:1,:3,:2]) # numpy slicing function
[[[0 1 2]
[3 4 5]
[6 7 8]]]
[[[0 1]
[3 4]
[6 7]]]
[[[0 1]
[3 4]
[6 7]]]
Upvotes: -1
Reputation: 515
You can access those elements using array slicing.
x = np.arange(9).reshape((1,3,3))
x[:, :, :2]
Upvotes: 2