How to Change the Number of Rows and Columns in an Array in Python 


               


How to Change the Number of Rows and Columns in an Array in Python



Python


In this article, we show how to change the number of rows and columns in an array in Python.

Let's say we have an array of 40 elements and this array is currently structured with 8 rows and 5 columns.

What if we want to change the layout of this array so that it will have 10 rows composed of 4 columns.

Python has a built-in function, reshape(), that allows us to reshape an array and change the rows and columns structure of the array.

So in the code below, we're going to show how to do this in Python.

In the code below, we create an original one-dimensional array.

We then reshape the array a few times.



So, first, we must import numpy as np, since we are using numpy to create an array.

Next, we create an array that goes from 0 to 39, so an array of 40 elements.

We then check to see the structure, or layout, of the array with the statement, array1.shape

In response, we get the output, (40,)

When the result is simply a single number followed by a comma, this means it is a one-dimensional array. There are no rows and columns. It's one-dimensional.

We want to reshape this one-dimensional array into a two-dimensional array that will have rows and columns.

We reshape this one-dimensional array into a two-dimensional array that will have 8 rows and 5 columns.

We then output the contents of this reshaped array which has 8 rows and 5 columns.

We then reshape the array again, this time into 10 rows that each contain 4 columns.

We then reshape the array into 4 rows containing 10 columns each.

So using the reshape() function in Python, we are able to change the number of rows and columns in an array in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...