How to Retrieve an Entire Row or Column of an Array in Python



Python


In this article, we show how to retrieve the entire row or column of an array in Python.

We use numpy arrays in this example.

So let's say that we create an array and we want to retrieve an entire row of this array. Or let's say we want to retrieve an entire column of the array. Below we go go over a complete example of this.



So let's now go over this code.

So the first thing we do is import numpy.

After this, we create an array consisting of 100 elements from 0 to 99 in rows and columns of 10 items each, 10 rows and 10 columns.

Now we want to be able to retrieve any column that we want. In this case, we want to retrieve all of the elements in column 2. To get all of the elements in a column, we use the format, arrayname[:, column_number], where arrayname is the name of the array and column_number is the number of the column whose contents you want to retrieve.

Since columns are normally vertical when displayed, you can change the format of the data by the reshape() function, converting the horizontal data into rows of 10 (for the data to look more like a column).

In this case, we want to retrieve all of the elements in row 2. To get all of the elements in a column, we use the format, arrayname[row_number,:], where arrayname is the name of the array and row_number is the number of the row whose contents you want to retrieve.

And this is how we can retrieve an entire row or column of an array in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...