Instruction: Describe a method for converting the data types of multiple DataFrame columns in a single operation.
Context: This question tests the candidate's efficiency in data preprocessing, specifically in optimizing the type conversion process across multiple columns.
Official answer available
Preview the opening of the answer, then unlock the full walkthrough.
Pandas provides a very efficient and versatile framework for managing and preprocessing data. When it comes to converting the data types of multiple columns within a DataFrame, my go-to method involves using the astype function. This function allows for the type conversion of multiple columns simultaneously, which is highly beneficial in terms of code efficiency and execution time.
Let's consider we have a DataFrame named df with columns 'A', 'B', 'C', where 'A' and 'B' are currently of type object, and 'C' is of type float64. Our goal is to convert 'A' to int64 and 'B' and 'C' to category. Here's how I would typically approach this:...