array.shape[1] , IndexError: tuple index out of range

One of the problem in python, when you are working with array is that you want to find the number of column of an array, but it just give you the number of row.

For example :

I start with a list, suppose that you have a list :

A =[5,9,3,15]

This is a simple vector that you will use in most python code. It is a 4 in 1 matrix. If you want to find the number of row, it is enough to write :

num_row = np.shape(A)

The result is a tuple :

num_row
Out[ ]: (4,)

As you see, it just contain the number of row and the number of column is not claculated.

The number of rows can be extracted as

num_row[0]

But, if you want to extract the number of columns,

num_row[1]
Traceback (most recent call last):

File "", line 1, in
num_row[1]

IndexError: tuple index out of range

In Stachoverflow, there are some solution, but these ways can not help

https://stackoverflow.com/questions/7670226/python-numpy-how-to-get-2d-array-column-length

Some python programmer, suggest using Numpy and numpy.array

If you use this way,

z3 = np.array([0,2,0])

and then the number of row works well :

z3.shape[0]

But the number of columns get error agian:

z3.shape[1]
Traceback (most recent call last):

File "", line 1, in
z3.shape[1]

IndexError: tuple index out of range

Solution :

You just need to add a simple option when you create an array the the problem is solved.

z3 = np.array([0,2,0],ndmin = 2)

In this way, you can calculate the number of rows and columns well.

z3.shape[0]
Out[]: 1

z3.shape[1]
Out[]: 3

It is recommended to use this way to define an array then you have full control over your variable in your code.

You can use the size method too.

np.size(z3,0)
Out[ ]: 1

np.size(z3,1)
Out[ ]: 3

Leave a Reply

Your email address will not be published. Required fields are marked *