Reshape and Transpose
- 02:31
How to reshape and transpose arrays in NumPy.
Downloads
No associated resources to download.
Glossary
NumPy Numpy arrays Python Reshaping TransposingTranscript
The array in that exercise was three rows in two columns. But what if you already had the array and then you needed to change it to two rows in three columns? Well, NumPy has a function called reshape that'll do exactly that.
To use the reshape function first, write the name of the array, which in this case is array one, and then dot reshape, and in parentheses, first the number of rows that you want. So two in this case, and second, the number of columns so three. And you can see that this has changed the shape of array one. Now an important note is that using the reshape function in this way doesn't change the original array. I can print array one still, and it comes out with three rows and two columns. If I wanna permanently reshape array one, I need to redefine it with the equal symbol. So I'll say array, array one is equal to array one dot reshape, and then my new dimension. So two rows, three columns. Now when I print array one, it's going to be in that new shape. Using the reshape function maintains the order of the objects in the original array. And to demonstrate that, we're gonna look at this little piece of code. NumPy also has a function called transpose, which is more of the traditional transpose that flips the order of the objects in the array, like you would use transpose in Excel. In this little piece of code I have here, first I'm starting by reshaping this array to the original dimensions, where it'll have three rows and two columns. Then I'm going to reshape into the array that we just saw, two rows and three columns. And for contrast, we're gonna look at transposing, the original array to two rows and three columns. So here are our original dimensions. We have three rows and two columns, and you can see it goes 1, 2, 3, 4, 5, 6. Like you're reading a book from left to right. When we reshape it from the original using the reshape function, we're still going from left to right, 1, 2, 3, 4, 5, 6. All of the objects in the array are in the same order. When you transpose, you can see that the order has been scrambled. Now it's 1, 3, 5, 2, 4, 6. Using each of these methods has a place it's important to know how to use both.