From the course: Python Functions for Data Science

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Reshape NumPy arrays

Reshape NumPy arrays

Being able to inspect and reorganize an array is crucial in data science, especially when preparing data for computations or machine-learning models. In this lesson, you'll learn how to check the dimensions of an array and reshape it into a new structure using .shape and .reshape. Let's start with importing NumPy and creating a simple two-dimensional array. To inspect this array's dimensions, use the .shape attribute. Do array.shape and print it out. This tells you that the array has two rows and three columns. Now you can change the shape of the array using the .reshape method. Here I'll convert this two-by-three array into a three-by-two array. I've called array.reshape and passed in 3, 2. When you reshape, the total number of elements must stay the same. The original array has six elements and the reshaped version also has six. You can also use negative one as a placeholder when you only want one dimension to be inferred automatically. Here I've used np.arange to define an array…

Contents