mas_bejo
mas_bejo

Reputation: 607

Take first dimension in ndarray python

Let's say I have a ndarray like this:

    a = [[20 43 61 41][92 23 43 33]]

I want take the first dimension of this ndarray. so I try something like this:

    a[0,:]

I hope it will return something like this:

    [[20 43 61 41]]

but i got this error:

   TypeError: 'numpy.int32' object is not iterable

Anyone can help me to solve this problem?

Upvotes: 6

Views: 13459

Answers (2)

NPE
NPE

Reputation: 500167

It's strange that you're getting this error. It suggests that a isn't what you think it is (i.e. not a Numpy array).

Anyway, here is how it can be done:

In [10]: import numpy as np

In [11]: a = np.array([[20, 43, 61, 41], [92, 23, 43, 33]])

In [12]: a[0:1]
Out[12]: array([[20, 43, 61, 41]])

Contrast this with

In [14]: a[0]
Out[14]: array([20, 43, 61, 41])

(which may or may not be what you want.)

Upvotes: 2

falsetru
falsetru

Reputation: 368894

Using slice:

>>> import numpy as np
>>> a = np.array([[20, 43, 61, 41], [92, 23, 43, 33]])
>>> a[:1]  # OR a[0:1]
array([[20, 43, 61, 41]])
>>> print(a[:1])
[[20 43 61 41]]

Upvotes: 2

Related Questions